單鏈表的反轉可以使用迴圈,也可以使用遞迴的方式
1.迴圈反轉單鏈表
迴圈的方法中,使用pre指向前一個結點,cur指向當前結點,每次把cur->next指向pre即可。
代碼:
# include <iostream># include <cstdlib>using namespace std;struct linkNode{int val;linkNode *next;linkNode(int x):val(x),next(NULL){}};linkNode *reverse2(linkNode *head){if(head==NULL)return NULL;linkNode *pre=NULL;linkNode *p=head;linkNode *h=NULL;while(p){h=p;linkNode *tmp=p->next;p->next=pre;pre=p;p=tmp;}return h; //返回頭結點}int main() //測試代碼{linkNode *head=new linkNode(1);linkNode *p1=new linkNode(2);linkNode *p2=new linkNode(3);head->next=p1;p1->next=p2; //建立鏈表 1->2->3->NULLlinkNode *p=reverse2(head);while(p){cout<<p->val<<endl;p=p->next;} //輸出為 3->2->1->NULLsystem("pause");return 0;}
2.遞迴實現單鏈表反轉
# include <iostream># include <cstdlib>using namespace std;struct linkNode{int val;linkNode *next;linkNode(int x):val(x),next(NULL){}};linkNode *reverse(linkNode *head,linkNode * &newhead) //head為原鏈表的頭結點,newhead為新鏈表的頭結點{ if(head==NULL)return NULL;if(head->next==NULL){newhead=head;}else{reverse(head->next,newhead);head->next->next=head;head->next=NULL;}return newhead;}int main() //測試代碼{linkNode *head=new linkNode(1);linkNode *p1=new linkNode(2);linkNode *p2=new linkNode(3);head->next=p1;p1->next=p2; //建立鏈表1->2->3->NULL;linkNode *newhead=NULL;linkNode *p=reverse(head,newhead); while(p){cout<<p->val<<endl;p=p->next;} //輸出鏈表 3->2->1->NULL;system("pause");return 0;}