單鏈表反轉C語言實現__C語言

來源:互聯網
上載者:User

單鏈表的反轉可以使用迴圈,也可以使用遞迴的方式

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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.