問題:
給定一個鏈表,請將其逆序。即如果鏈表原來為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;}