前言
前面学习了线性表的顺序数组实现,那便想到线性表肯定还有链表实现,今天就来看看线性表的单链表实现。
线性表的单链表实现
模板基类:
template<class elemType>
class list
{
public:
virtual void clear() = 0; //clear all elements in list
virtual int length()const = 0; //get the length of list
virtual void insert(int i, const elemType &x) = 0; //insert an element in list
virtual void remove(int i) = 0; //remove an list in list
virtual int search(const elemType &x)const = 0; //search the element
virtual elemType visit(int i)const = 0; //visit the element
virtual void traverse()const = 0; //visit every element in list
virtual ~list(){};
};
子类线性表的单链表实现:
template<class elemType>
class sLinkList:public list<elemType>{
private:
struct node{
elemType data;
node *next;
node(const elemType &x, node *n = NULL){
data = x;
next = n;
}
node():next(NULL){}
~node(){}
};
node *head;
int currentLength;
node *move(int i)const{
node *p = head;
while(i >= 0){
p = p -> next;
i = i - 1;
}
return p;
}
public:
sLinkList(){
head = new node;
currentLength = 0;
}
~sLinkList(){
clear();
delete head;
}
void clear(){
node *p, *q;
p = head -> next;
head -> next = NULL;
while(p != NULL){
q = p;
p = p -> next;
delete q;
}
currentLength = 0;
}
int length()const{
return currentLength;
}
void insert(int i, const elemType &x){
node *p = move(i - 1);
p = new node(x, p -> next);
currentLength = currentLength + 1;
}
void remove(int i){
node *p = move(i - 1);
node *q = p -> next;
p -> next = q -> next;
delete q;
currentLength = currentLength - 1;
}
elemType search(const elemType &x)const{
int k = 0;
node *p = head -> next;
while(p != NULL){
if(p -> data == x){
return k;
}
p = p -> next;
k = k + 1;
}
return -1;
}
elemType visit(int i)const{
return (move(i)) -> data;
}
void traverse()const{
node *p = head -> next;
while(p != NULL){
cout << p -> data << " ";
p = p -> next;
}
cout << endl;
}
};
总结
从链表运算的实现来看,在顺序表中性能很好的visit(i)在链表中的时间复杂度为O(N),而在顺序表中性能较差的插入删除操作在链表中具有较好的性能。对于单链表而言,如果当前指针已经定位到插入或删除位置的前一个位置,则插入和删除都只需要常量的时间。所以链表适合那些经常需要执行插入删除但很少访问制定位置元素的线性表。
以上内容纯属个人学习总结,不代表任何团体或单位。