#ifndef __LIST__
#define __LIST__
#include<iostream>
using namespace std;
#ifndef DEFAULT_SIZE
#define DEFAULT_SIZE 10
#endif
template<class T>
class SeqList
{
public:
SeqList();
SeqList(int size);
~SeqList();
public:
int GetLength() const;
int LocateItem(T x) const; //定位数据 返回在顺序表中的位置
void InsertItem(T x, int i);//在指定位置 插入数据
void InsertTail(T x);
void DeleteItem(T x);
void DeleteTail();
T& GetItem(int i);
void SetItem(T x, int i);
public:
int IsEmpty();
int IsFull();
int IsIn(T x); //判断数据是否在顺序表中
public:
void Show();
public:
T* data;
int MAXSIZE;
int last;
};
#endif
template<class T>
SeqList<T>::SeqList()
{
MAXSIZE = DEFAULT_SIZE;
last = -1;
data = new T[MAXSIZE];
}
template<class T>
SeqList<T>::~SeqList()
{
if (data)
{
delete []data;
}
}
template<class T>
SeqList<T>::SeqList(int size)
{
if (size<=0)
{
MAXSIZE = 0;
last = -1;
data = NULL;
}else{
MAXSIZE = size;
last = -1;
data = new T[MAXSIZE];
}
}
template<class T>
void SeqList<T>::InsertItem(T x, int i)
{
if ((i-1)<0 || i>=MAXSIZE ||(i-1)>last || IsFull())
{
return;
}
for (int index=last; index>=(i-1); index--)
{
data[index+1] = data[index];
}
data[i-1] = x;
last++;
}
template<class T>
void SeqList<T>::InsertTail(T x)
{
if ((last==MAXSIZE-1) || IsFull())
{
return;
}
data[++last] = x;
}
template<class T>
void SeqList<T>::DeleteItem(T x)
{
int i = LocateItem(x);
if ((i-1)>=0)
{
for (int index=i-1; index<=last; index++)
{
data[index] = data[index+1];
}
last--;
}
}
template<class T>
void SeqList<T>::DeleteTail()
{
if (last>=0)
{
last--;
}
}
template<class T>
int SeqList<T>::LocateItem(T x) const
{
for (int i=0; i<last; i++)
{
if (data[i] == x)
{
return i+1;
}
}
return 0;
}
template<class T>
int SeqList<T>::GetLength() const
{
return last+1;
}
template<class T>
void SeqList<T>::SetItem(T x, int i)
{
if ((i-1)<0 || last==-1 || (i-1)>last)
{
return;
}
data[i-1] = x;
}
template<class T>
T& SeqList<T>::GetItem(int i)
{
if (i<0 || i>last)
{
return NULL;
}
return data[i];
}
template<class T>
int SeqList<T>::IsIn(T x)
{
for (int i=0; i<=last; i++)
{
if (data[i] == x)
{
return 1;
}
}
return 0;
}
template<class T>
int SeqList<T>::IsFull()
{
return last == MAXSIZE;
}
template<class T>
int SeqList<T>::IsEmpty()
{
return last == -1;
}
template<class T>
void SeqList<T>::Show()
{
cout << "共有" << last+1 << "个元素:" << endl;
for (int i=0; i<=last; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
#include "List.h"
#include <iostream>
using namespace std;
int main()
{
SeqList<int> ls(5);
ls.InsertTail(3);
ls.InsertTail(9);
ls.InsertTail(8);
ls.InsertItem(100, 2);
ls.SetItem(99, 1);
ls.Show();
cout << "--------------\n";
ls.DeleteItem(99);
ls.Show();
cout << "--------------\n";
ls.DeleteTail();
ls.Show();
if (ls.IsIn(100))
{
cout << ls.LocateItem(100) << endl;
}
system("pause");
return 0;
}