?? p2-135.cpp
字號(hào):
#include<iostream.h>
//定義節(jié)點(diǎn)(數(shù)據(jù)對(duì)象)的接口
class Node
{
//聲明list類為本類的友元類
friend class list;
//私有成員
private:
int Data; //節(jié)點(diǎn)數(shù)據(jù)
Node *previous; //前趨指針
Node *next; //后繼指針
};
//定義雙向鏈表list的接口聲明
class list
{
//私有成員
private:
Node *Head; //鏈表頭指針
Node *Tail; //鏈表尾指針
//定義接口函數(shù)
public:
//構(gòu)造函數(shù)
list();
//析構(gòu)函數(shù)
~list();
//從鏈表尾后添加數(shù)據(jù)
void Build_HT(int Data);
//從鏈表前頭添加數(shù)據(jù)
void Build_TH(int Data);
//從頭到尾顯示數(shù)據(jù)
void list::Display_HT();
//從尾到頭顯示數(shù)據(jù)
void list::Display_TH();
//清除鏈表的全部數(shù)據(jù)
void Clear();
};
//main()函數(shù)測(cè)試雙向鏈表
int main(void)
{
list list1;
int i;
//從尾添加數(shù)據(jù)
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;
//從頭添加數(shù)據(jù)
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類函數(shù)的定義
//構(gòu)造函數(shù)的定義
list::list()
{
//初值
Head=0;
Tail=0;
}
//析構(gòu)函數(shù)的定義
list::~list()
{
Clear();
}
//從鏈表尾后添加數(shù)據(jù)
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;
}
}
//從鏈表前頭添加數(shù)據(jù)
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;
}
}
//從頭到尾顯示數(shù)據(jù)
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;
}
//從尾到頭顯示數(shù)據(jù)
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;
}
//清除鏈表的全部數(shù)據(jù)
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);
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -