[cpp]
#include<iostream.h>
//定義節點(數據對象)的接口
class Node
{
//聲明list類為本類的友元類
friend class list;
//私有成員
private:
int Data; //節點數據
Node *previous; //前趨指針
Node *next; //後繼指針
};
//定義雙向鏈表list的接口聲明
class list
{
//私有成員
private:
Node *Head; //鏈表頭指針
Node *Tail; //鏈表尾指針
//定義接口函數
public:
//構造函數
list();
//析構函數
~list();
//從鏈表尾後添加數據
void Build_HT(int Data);
//從鏈表前頭添加數據
void Build_TH(int Data);
//從頭到尾顯示數據
void list::Display_HT();
//從尾到頭顯示數據
void list::Display_TH();
//清除鏈表的全部數據
void Clear();
};
//main()函數測試雙向鏈表
int main(void)
{
list list1;
int i;
//從尾添加數據
cout<<"Add to the back of the list1:"<<endl;
for (i=1;i<=20;i=i+2) {
list1.Build_HT(i);
cout<<i<<" ";
}
cout<<endl;
//從頭添加數據
cout<<"Add to the front of the list1:"<<endl;
for (i=0;i<=20;i=i+2) {
list1.Build_TH(i);
cout<<i<<" ";
}
cout<<endl;
//顯示鏈表
list1.Display_HT();
list1.Display_TH();
return 0;
}
//list類函數的定義
//構造函數的定義
list::list()
{
//初值
Head=0;
Tail=0;
}
//析構函數的定義
list::~list()
{
Clear();
}
//從鏈表尾後添加數據
void list::Build_HT(int Data)
{
Node *Buffer;
Buffer=new Node;
Buffer->Data=Data;
if(Head==0)
{
Head=Buffer;
Head->next=0;
Head->previous=0;
Tail=Head;
}
else
{
Tail->next=Buffer;
Buffer->previous=Tail;
Buffer->next=0;
Tail=Buffer;
}
}
//從鏈表前頭添加數據
void list::Build_TH(int Data)
{
Node *NewNode;
NewNode=new Node;
NewNode->Data=Data;
if(Tail==0)
{
Tail=NewNode;
Tail->next=0;
Tail->previous=0;
Head=Tail;
}
else
{
NewNode->previous=0;
NewNode->next=Head;
Head->previous=NewNode;
Head=NewNode;
}
}
//從頭到尾顯示數據
void list::Display_HT()
{
Node *TEMP;
TEMP=Head;
cout<<"Display the list from Head to Tail:"<<endl;
while(TEMP!=0)
{
cout<<TEMP->Data<<" ";
TEMP=TEMP->next;
}
cout<<endl;
}
//從尾到頭顯示數據
void list::Display_TH()
{
Node *TEMP;
TEMP=Tail;
cout<<"Display the list from Tail to Head:"<<endl;
while(TEMP!=0)
{
cout<<TEMP->Data<<" ";
TEMP=TEMP->previous;
}
cout<<endl;
}
//清除鏈表的全部數據
void list::Clear()
{
Node *Temp_head=Head;
if (Temp_head==0) return;
do
{
Node *TEMP_NODE=Temp_head;
Temp_head=Temp_head->next;
delete TEMP_NODE;
}
while (Temp_head!=0);
}