[程式員面試題精選100題]19.反轉鏈表,程式員試題

來源:互聯網
上載者:User

[程式員面試題精選100題]19.反轉鏈表,程式員試題

題目

輸入一個鏈表的頭結點,反轉該鏈表,並返回反轉後鏈表的頭結點。

分析


假設經過若干操作,我們已經把結點 pre之前的指標調整完畢,這些結點的next指標都指向前面一個結點。現在我們遍曆到結點cur。我們需要把調整結點的next指標讓它指向前一個結點pre。注意一旦調整了指標的指向,鏈表就斷開了,如所示:

因為已經沒有指標指向結點nextNode,我們沒有辦法再遍曆到結點nextNode 了。因此為了避免鏈表斷開,我們需要在調整cur的next指標之前要把nextNode儲存下來。

代碼

/*---------------------------------------------*   日期:2015-02-11*   作者:SJF0115*   題目: 19.反轉鏈表*   來源:程式員精選100題*   部落格:-----------------------------------------------*/#include <iostream>using namespace std;struct ListNode{    int val;    ListNode *next;    ListNode(int x):val(x),next(NULL){}};// 輸出void Show(ListNode *head){    ListNode *p = head;    while(p){        cout<<p->val<<"->";        p = p->next;    }//while    cout<<"nullptr"<<endl;}class Solution {public:    void ReverseList(ListNode* &head){        if(head == NULL){            return;        }//if        ListNode *pre = NULL,*cur = head,*nextNode;        while(cur){            nextNode = cur->next;            cur->next = pre;            // 前移一個節點            pre = cur;            cur = nextNode;        }//while        head = pre;    }//void};int main() {    Solution solution;    ListNode *head = new ListNode(1);    ListNode *node,*p;    p = head;    for(int i = 2;i <= 8;++i){        node = new ListNode(i);        p->next = node;        p = node;    }//for    Show(head);    solution.ReverseList(head);    Show(head);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.