鏈表逆序演算法

來源:互聯網
上載者:User
問題:

給定一個鏈表,請將其逆序。即如果鏈表原來為1->2->3->4->5->null,逆序後為5->4->3->2->1->null.

解法1:迭代演算法迭代演算法效率較高,但是代碼比遞迴演算法略長。遞迴演算法雖然代碼量更少,但是難度也稍大,不細心容易寫錯。迭代演算法的思想就是遍曆鏈表,改變鏈表節點next指向,遍曆完成,鏈表逆序也就完成了。代碼如下:
struct node {    int data;    struct node* next;};typedef struct node* pNode;pNode reverse(pNode head){    pNode current = head;    pNode next = NULL, result = NULL;    while (current != NULL) {        next = current->next;        current->next = result;        result = current;        current = next;    }    return result;}

如果不傳回值,可以傳遞參數改為指標的指標,直接修改鏈表的頭結點值(如果在C++中直接傳遞引用更方便),可以寫出下面的代碼:

void reverse2(struct node** headRef){       pNode current = *headRef;    pNode next = NULL, result = NULL;    while (current != NULL) {        next = current->next;        current->next = result;        result = current;        current = next;    }    *headRef = result;}
解法2:遞迴演算法遞迴演算法實現原理:假定原鏈表為1,2,3,4,則先逆序後面的2,3,4變為4,3,2,然後將節點1連結到已經逆序的4,3,2後面,形成4,3,2,1,完成整個鏈表的逆序。代碼如下:
void reverseRecur(struct node** headRef){    if (*headRef == NULL)  return;    pNode first, rest;    first = *headRef;       //假定first={1,2,3,4}    rest = first->next;   // rest={2,3,4}    if (rest == NULL) return;    reverseRecur(&rest); //rest逆序後變成{4,3,2}    first->next->next = first; //將第一個節點置於逆序後鏈表最後    first->next = NULL;    *headRef = rest;  //更新頭結點}

如果使用C++的參考型別,代碼會稍顯簡單點,代碼如下:

void reverseRecur(pNode& p){if (!p) return; pNode rest = p->next;  if (!rest) return;  reverseRecur(rest);  p->next->next = p;  p->next = NULL;  p = rest;}

聯繫我們

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