單向鏈表 頭尾插法
#include<iostream.h>#include<conio.h> struct node{ int data; node *next; };node *createlist(int );node *createlistinvert(int );void outputlist(node *head); int main(){ int n; node *listhead=NULL; cout<<"請輸入節點數目: "; cin>>n; cout<<"**************下面請您輸入"<<n<<"個整數*****************\n"<<endl; if(n>0) { cout<<" ***************尾差法********************\n"<<endl; listhead=createlist(n); outputlist(listhead); cout<<" \n\n *****************頭插法*********************\n"<<endl; cout<<"**************下面請您輸入"<<n<<"個整數*****************\n"<<endl; listhead=createlistinvert(n); outputlist(listhead); } getch(); return 0; }//尾插法 node *createlist(int n){ node *temp=NULL,*tail=NULL,*head=NULL; int num; cout<<"請輸入資料: "; cin>>num; head=new node; if(head==NULL) { cout<<"記憶體配置不成功,重試吧!"; return NULL; } else { head->data=num; head->next=NULL; tail=head; } for(int i=0;i<n-1;i++) { cin>>num; temp=new node; if(temp==NULL) { cout<<"記憶體配置不成功"; return head; } else { temp->data=num; temp->next=NULL; tail->next=temp; tail=temp; } } return head; }//頭插法node *createlistinvert(int n){ node *temp=NULL,*head=NULL; cout<<"請輸入資料:"; int num; cin>>num; head=new node; if(head==NULL) { cout<<"記憶體配置不成功!"; return NULL; } else { head->data=num; head->next=NULL; } for(int i=0;i<n-1;i++) { cin>>num; temp=new node; if(temp==NULL) { cout<<"記憶體配置不成功!"; return head; } else { temp->data=num; temp->next=head; head=temp; } } return head; } void outputlist(node *head) { cout<<"List: "; node *curnode=head; while(curnode) { cout<<curnode->data; if(curnode->next) cout<<" -> "; curnode=curnode->next; } cout<<endl; }