SeqList.h
#pragma once
#include <iostream>
#include <cassert>
#define N 200
typedef int SLDatatype;
using namespace std;
/*
顺序表:在计算机内存中以数组形式保存的线性表,采用顺序存储结构(数据元素物理存储地址相邻)
*/
//动态顺序表
template<typename t>
class SeqList {
t* ptr; //动态数组指针
t data;//传入数据
int size;//数据个数
int capacity;//容量-空间大小(可容纳的数据个数)
public:
SeqList();
void PushBack(t data);//后添加
void SLPrint();//打印
void SLDelete();//销毁
void SLPushFront(t Data);//头插
void SLPopFront();//头删
void SLInsert(t data, int pos);//插值
void SLErase(int pos);//删除某个值
int SLFind(t data);//查找某个值位置
void Modify(t data, int pos);//修改某个位置的值
private:
void CheckCapacity(); //扩容
};
template<typename t>
inline SeqList<t>::SeqList()
{
this->ptr = nullptr;
this->size = this->capacity = 0;
}
template<typename t>
void SeqList<t>::CheckCapacity()
{
if (this->size == this->capacity)
{
this->capacity = this->capacity + 1;
t* tmp = (t*)realloc(this->ptr, this->capacity * sizeof(t));
if (tmp == NULL)
{
perror("relloc:");
exit(-1);
}
this->ptr = tmp;
}
}
template<typename t>
void SeqList<t>::PushBack(t data)
{
this->CheckCapacity();
this->ptr[this->size] = data;
this->size++;
}
template<typename t>
void SeqList<t>::SLPrint()
{
cout << "seqlist: ";
for (int i = 0; i < this->size; i++)
{
cout << " " << this->ptr[i];
}
cout << endl;
}
template<typename t>
void SeqList<t>::SLDelete()
{
if (this->ptr)
{
free(this->ptr);
this->ptr = NULL;
this->size = this->capacity = 0;
cout << "delete success" << endl;
}
else
{
cout << "delete unfinished...." << endl;
}
}
template<typename t>
void SeqList<t>::SLPushFront(t data)
{
this->CheckCapacity();
int end = this->size - 1;
while (end >= 0) {
this->ptr[end + 1] = this->ptr[end];
end--;
}
this->ptr[0] = data;
this->size++;
}
template<typename t>
void SeqList<t>::SLPopFront()
{
assert(this->size);
int begin = 1;
while (begin < this->size)
{
this->ptr[begin - 1] = this->ptr[begin];
begin++;
}
this->size--;
}
template<typename t>
void SeqList<t>::SLInsert(t data, int pos)
{
assert(pos >= 0 && pos <= this->size);
CheckCapacity();
int end = this->size - 1;
while (end >= pos)
{
this->ptr[end + 1] = this->ptr[end];
end--;
}
this->ptr[pos] = data;
this->size++;
}
template<typename t>
void SeqList<t>::SLErase(int pos)
{
assert(pos >= 0 && pos <= this->size);
int begin = pos + 1;
while (begin < this->size)
{
this->ptr[begin - 1] = this->ptr[begin];
begin++;
}
this->size--;
}
template<typename t>
int SeqList<t>::SLFind(t data)
{
for (int i = 0; i <= this->size; i++)
{
if (this->ptr[i] == data)
return i;
}
return -1;
}
template<typename t>
void SeqList<t>::Modify(t data, int pos)
{
assert(pos >= 0 && pos < this->size);
this->ptr[pos] = x;
}