自己参考书籍写的双向链表模板代码:
#include
#include
#ifndef LIST_H
#define LIST_H
template
class List
{
private:
struct Node
{
Node* front;
Node* next;
T item;
};
Node* first;
Node* rear;
int listsize;
public:
List();
~List();
bool isempty();//判断空链表
bool isfull();//判断是否满
int length();
bool insert(T &t);//尾部追加元素
bool findinsert(T &t1,T &t2);//查找插入元素:在t1之后插入t2
bool denode(T &t);//按查找内容删除元素
void display();//显示链表元素的item
};
template
List::List()
{
first=rear=0;//空指针最好使用0赋值,NULL不建议使用
listsize=0;
};
template
List::~List()
{
Node* tem;
while(first)
{
tem=first->next;
delete first;
first=tem;
}
}
template
int List::length()
{
int i=0;
Node* temp=new Node;
temp=first;
temp->next=first->next;
temp->front=0;
while(temp)
{
temp=temp->next;
i++;
}
cout<<"链表长度为: "<
bool List::findinsert(T &t1,T &t2)//按查找位置插入元素
{
Node* add=new Node;
add->item=t2;
Node* temp=new Node;
temp=first;
temp->next=first->next;
temp->front=0;
while(temp)
{
if(temp->item==t1)
{
add->next=temp->next;//把查找到的元素的next赋值给add的next
temp->next=add;//将查找到的元素的next指向add
add->front=first;//将add的前指针指向查找到的元素
add->next->front=add;//将查找到的元素的下一个元素的front指向add;
temp=0;
}
else
temp=temp->next;
}
return true;
}
template
bool List::insert(T &t)//尾部追加元素
{
Node* add=new Node;
add->item=t;
add->next=0;
if(first==0)//空链表
{
first=add;
rear=first;
}
else
{
rear->next=add;
add->front=rear;
rear=add;
rear->front=add->front;
rear->next=0;
}
return true;
}
template
bool List::denode(T &t)//删除所有iten为t的节点
{
Node* temp=new Node;
Node* dele=new Node;
dele->front=dele->next=0;
dele->item=NULL;
temp=first;
temp->next=first->next;
temp->front=0;
while(temp)
{
if(temp->item==t)
{
dele=temp;
temp->front->next=temp->next;
temp->next->front=temp->front;
temp=temp->next;
delete dele;
}
else
{
temp=temp->next;
}
}
return true;
}
template
void List::display()//显示链表
{
if(first==0)
{
cout<<"空链表\n";
}
else
{
while(first)
{
cout<item<<",";
first=first->next;
}
}
}
#endif
int arr[10]= {10,5,8,7,6,5,4,3,5,1};
int a=5;
int b=100;
List list;
for(int i=0; i<10; ++i)
{
list.insert(arr[i]);
}
list.findinsert(a,b);
list.length();
list.denode(a);
list.display();
system("pause");