【演算法題】寫一個遞迴版本的鏈錶轉置程式

來源:互聯網
上載者:User

鏈表的轉置是一個很常見、很基礎的資料結構題了,非遞迴的演算法很簡單,用三個臨時指標在鏈表上迴圈一遍即可,不再贅述。遞迴演算法也是比較簡單的,但是如果思路不清晰估計也難一時半會兒寫出來把。下面是遞迴版本的鏈錶轉置程式:

#include <iostream>using namespace std;typedef struct Node{    Node(int v, Node *ptr=NULL) : data(v), next(ptr) {}    int data;    Node *next;}sNode;//LB_c: 輸出鏈表,head為鏈表頭指標void outputList(sNode *head){    sNode *p = head;    while (p != NULL)    {cout << p->data << " -> ";p = p->next;    }    cout << "NULL" << endl;}//LB_c: 轉置鏈表的遞迴方法實現sNode* reverseList(sNode *head){    //LB_c: 異常判斷(NULL==head)結束條件(NULL==head->nex),    // 即head為最後一個節點時,將該節點返回,即為轉置鏈表的前端節點。    if ( (NULL == head) || (NULL == head->next) )return head;    //LB_c: 遞迴後續鏈表(即以head->next為首節點的鏈表)    sNode *pNewHead = reverseList(head->next);    //LB_c: 上一步執行完後,head->next為後續鏈表的末尾節點,    //所以讓head->next的next指向當前節點head    head->next->next = head;    //LB_c: 當前節點的next指向NULL    head->next = NULL;    //LB_c: 返回後續鏈表的頭指標    return pNewHead;}int main(){    //LB_c: 建立鏈表    sNode n5(5);    sNode n4(4, &n5);    sNode n3(3, &n4);    sNode n2(2, &n3);    sNode n1(1, &n2);    //LB_c: 輸出原始鏈表    outputList(&n1);    //LB_c: 調用轉置函數    sNode *pNew = reverseList(&n1);    //LB_c: 輸出轉置後的鏈表    outputList(pNew);    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.