#include<iostream> using namespace std; struct node{ int d; struct node *next; };//定義結點 node *build1()//頭插法構造單鏈表 { node *p;//指向新建結點 node *head;//頭指針 head=NULL; p=head; int x; cin>>x; while(x!=-1) { p=new node; p->d=x; p->next=head; head=p; cin>>x; } return head; } node *build2()//尾插法構造單鏈表 { node *head;//頭指針 node *p,*s;//p指向當前結點,s指向尾結點 head=NULL; p=head; s=head; int x; cin>>x; while(x!=-1) { p=new node; p->d=x; if(!head)head=p; else s->next=p; s=p; cin>>x; } if(s)s->next=NULL; return head; } int main() { node *p; p=build2(); while(p!=NULL) { cout<<(p->d); p=p->next; } return 0; }
建立單鏈表的方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.