擴展問題: 編寫一個函數,給定一個鏈表的頭指針,要求只遍歷一次,將單鏈表中的元素順序反序。 #include <iostream> #include <string> #include <algorithm> #include <cstring> using namespace std; struct node{ int data; node *next; }; void reverselist(node* &head) { node *p,*q; p=head->next; q=head->next->next; if(q==NULL)return; //若鏈表只有一個元素,則不操作 p->next=NULL; while(q->next!=NULL) { node *tmp=q->next; q->next=p; p=q; q=tmp; } q->next=p; head->next=q; //將表頭指針調轉 } void destroy(node* &head) { node *p=head; head=head->next; while(head->next!=NULL) { delete p; p=head; head=head->next; } delete p; delete head; } int main() { node *head=new node; head->next=NULL; int n; cin>>n; while(n--) { node *pt=new node; cin>>pt->data; pt->next=head->next; head->next=pt; } reverselist(head); //此時簡歷的鏈表是輸入的逆序,所以倒序後成為輸入的正序 node *pt=head->next; while(pt->next!=NULL) { cout<<pt->data<<" "; pt=pt->next; } cout<<pt->data<<endl; destroy(head); //記得資源回收 return 0; } #include <iostream> #include <string> #include <algorithm> #include <cstring> using namespace std; struct node{ int data; node *next; }; void reverselist(node* &head) { node *p,*q; p=head->next; q=head->next->next; if(q==NULL)return; //若鏈表只有一個元素,則不操作 p->next=NULL; while(q->next!=NULL) { node *tmp=q->next; q->next=p; p=q; q=tmp; } q->next=p; head->next=q; //將表頭指針調轉 } void destroy(node* &head) { node *p=head; head=head->next; while(head->next!=NULL) { delete p; p=head; head=head->next; } delete p; delete head; } int main() { node *head=new node; head->next=NULL; int n; cin>>n; while(n--) { node *pt=new node; cin>>pt->data; pt->next=head->next; head->next=pt; } reverselist(head); //此時簡歷的鏈表是輸入的逆序,所以倒序後成為輸入的正序 node *pt=head->next; while(pt->next!=NULL) { cout<<pt->data<<" "; pt=pt->next; } cout<<pt->data<<endl; destroy(head); //記得資源回收 return 0; }