天天看點

資料結構 P35 算法實作 循環連結清單的建立與查找

#include<iostream>

using namespace std;

struct node            //建立節點

{

int date;

node *next;

};

int main()

{

node *head;               //建立頭結點

head=NULL;

int x=1,y1=0;          //y1為判斷連結清單現有長度的參數

node *p,*s;

while(x<9)              //自動建立資料為1-8的連結清單

{

s=new node();    //動态配置設定新的節點

s->date=x;        //給新節點的資料指派

if(head==NULL) //如果沒有頭結點則将第一個新節點作為頭結點

{ s->next=NULL;

p=head=s;}

else                  

{ s->next=head; //将新節點的下一個節點設為頭結點

p->next=s;   //将新節點設為連結清單尾部的下一個節點

p=p->next;}

++x;++y1;}

cout<<"連結清單為:";        //列印連結清單

p=head;

cout<<p->date<<" ";        //列印頭結點

p=p->next;                        //節點後移一個

for(;p!=head&&p!=NULL;p=p->next) //當節點不是頭結點或者節點不為空(避免連結清單隻有一個頭結點)時列印該節點的資料,然後将節點後移一個

cout<<p->date<<" ";

cout<<endl;

while(1)                //在連結清單中查詢存儲該資料的節點的下一個節點所存儲的資料

{

int y,y2=1; //y2為已周遊連結清單的長度

cin>>y;     //輸入需要查詢的節點

for(p=head;p->next!=head&&p->next!=NULL;p=p->next) //當節點的下一個節點不是頭結點或者不為空時(避免連結清單隻有一個頭結點)執行查詢程式,然後節點後移一位

{

if(y==p->date)  //當查詢的資料與目前節點所存儲的資料一緻時 退出for循環

break;

++y2;

}

if(y1==y2) //若周遊連結清單查詢不到所輸入的資料

cout<<"連結清單中沒有你所輸入的資料!!!"<<endl;

else

{   p=p->next;

cout<<"下一個為:"<<p->date<<endl;}

}

return 0;

}