线性表的基本操作
线性表的类定义
template <class T>
class LinearList
{
public:
LinearList();
int Length();
int Locate(int i);
void Insert(int i, T &x);
void Delete(int i, T &x);
bool IsEmpty();
bool IsFull();
T getData(int i, T &x);
}
顺序表的类定义
template <class T>
class SeqList : public LinearList<T>
{
private:
T *data;
int maxSize;
int last;
public:
SeqList(int sz):maxSize(sz){}
int Length();
void Insert(T &x, int i);
void Remove(T &x, int i);
bool IsEmpty(){return last == -1;}
bool IsFull(){return last == maxSize - 1;}
T getData(T &x, int i);
}
template <class T>
T SeqList<T :: getData(T &x, int i)
{
if(i > 0 && i < last+1)
{
x = data[i-1];
return x;
}
}
template <class T>
void SeqList<T> :: Insert(T &x, int i)
{
for(int j = last; j >= i; j--)
data[j+1] = data[j];
data[i] = x;
last++;
}
template <class T>
void SeqList<T> :: Remove(T &x, int i)
{
for(int j = i; j <= last;j++)
data[j-1] = data[j];
last--;
}
单链表
链表结点的定义
template <class T>
struct ListNode
{
T data;
ListNode<T> *next;
};
链表类的定义
template <class T>
class List : public LinearList<T>
{
private:
ListNode<T *head;
public:
void Insert(T &x, int i);
void Remove(T &x, int i);
int Length();
ListNode<T> *Locate(int i);
bool IsEmpty(){return head -> next == NULL ? true:false;}
void makeEmpty();
}
template <class T>
void List<T> :: makeEmpty()
{
ListNode<T *q;
while(head -> next != NULL)
{
q = head -> next;
head -> next = q -> next;
delete q;
}
}
template <class T>
int List<T> :: Length()
{
ListNode<T> *p = head -> next;
int count = 0;
while(p != NULL)
{
count++;
p = p -> next;
}
return count;
}
template <class T>
ListNode<T>* List<T> :: Locate(int i)
{
ListNode<T> *p = head;
int k = 0;
while(p != NULL && k < i)
{
p = p -> next;
k++;
}
return p;
}
template <class T>
void List<T> :: Insert(T &x, int i)
{
if(head -> next == NULL || i == 0)
{
ListNode *newNode = new ListNode(x);
newNode -> next = head -> next;
head -> next = newNode;
}
else
{
ListNode *current = head -> next;
for(int k = 1; k < i; k++)
if(current == NULL)
break;
else
current = current -> next;
ListNode *newNode = new ListNode(x);
newNode -> next = current -> next;
current -> next = newNode;
}
}
void List<T> :: Remove(T &x, int i)
{
ListNode *del, *current;
if(i <= 1)
{
del = head -> next;
head -> next = NULL;
}
else
{
for(int k = 1; k < i-1; k++)
if(current == NULL)
break;
else
current = current -> next;
del = current -> next;
current -> next = del -> next;
}
delete del;
}
双向链表的插入和删除算法
void DoubleList<T> :: Insert(T &x, int i, int d)
{
DoubleNode *p = head -> next;
int j = 0;
while(p != NULL && j <i)
{
p = p -> next;
j++;
}
DoubleNode<T> *newNode = new DoubleNode<T>(x);
if(d == 0) /*前驱方向插入*/
{
newNode -> lnext = p -> lnext;
p -> lnext = newNode;
newNode -> lnext -> rnext = newNode;
newNode -> rnext = p;
}
else /*后继方向插入*/
{
newNode -> rnext = p -> lnext;
p -> rnext = newNode;
newNode -> rnext -> lnext = newNode;
newNode -> lnext = p;
}
}