單鏈表的逆序方法有不少種,求職過程當中會碰到相似的題。好比進棧出棧;變量鏈表放入數組後利用數組的逆序重構鏈表;遍歷鏈表時每次訪問的節點都指向它的前節點;遞歸調用等。本次實驗是用遞歸的方法實現單鏈表的逆序,網上有不少相似的code.html
此次實驗主要要注意的是指針引用的使用,要充分理解引用是個別名,指針的引用能夠參考其它網友的一篇博文:指針的引用ios
實驗內容是先構造一個隨機指定長度的單鏈表,將其輸出,而後逆序後輸出。數組
代碼以下:dom
// reverse_list.cpp : 定義控制檯應用程序的入口點。 // #include "stdafx.h" #include <iostream> #include <stdlib.h> #include <random> using namespace std; struct Node { int vale; Node *next; }; /*建立長度爲n的一個隨機整數鏈表*/ Node* creat_list(int n) { Node *head = new Node; head->next = NULL; Node *pre = head; srand(0); for(int i = 0; i < n; i++) { Node *current = new Node; current->vale = rand(); current->next = NULL; pre->next = current; pre = current; } return head; } /*鏈表的逆序*/ Node* reverse_list(Node *plist, Node *&head) //這個函數的返回值並非最終鏈表逆序後的鏈表頭,而是尾, //它的頭保存在head指針裏,因此head用的是指針引用. { Node *pback = NULL; if(plist == NULL || plist->next == NULL) { head->next = plist; return plist; } else { pback = reverse_list(plist->next, head); pback->next = plist; return plist; } } /*從頭節點依次顯示鏈表裏的元素,注意這裏頭節點裏的元素沒有被當作第一個元素*/ void show_list(Node *p) { while(p->next != NULL) { cout<<p->next->vale<<" "; p = p->next; //由於每一個結構體的節點不是以數組的形式存在,因此其地址不是連續的,不能用p++ } cout<<endl; } int _tmain(int argc, _TCHAR* argv[]) { int n = 10; Node *my_list = creat_list(n); cout<<"My list is : "<<endl; show_list(my_list); Node *head = new Node; cout<<"My reverse_list is : "<<endl; reverse_list(my_list->next, head)->next = NULL; show_list(head); return 0; }
實驗結果以下:函數
參考資料:post
指針的引用url