算法設計和數據結構學習_6(單鏈表的遞歸逆序)


  

  單鏈表的逆序方法有很多種,求職過程中會碰到類似的題。比如進棧出棧;變量鏈表放入數組后利用數組的逆序重構鏈表;遍歷鏈表時每次訪問的節點都指向它的前節點;遞歸調用等。本次實驗是用遞歸的方法實現單鏈表的逆序,網上有很多類似的code.

  這次實驗主要要注意的是指針引用的使用,要充分理解引用是個別名,指針的引用可以參考其它網友的一篇博文:指針的引用

  實驗內容是先構造一個隨機指定長度的單鏈表,將其輸出,然后逆序后輸出。

  代碼如下:

// 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;
}

 

  實驗結果如下:

   

 

   參考資料:

  指針的引用

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM