單鏈表倒序的遞歸與非遞歸實現


在各大公司面試中,通常會遇到的最基本的算法題之一是單鏈表的倒序問題。在此僅介紹最常用的且復雜度相對較低的方法。

leetcode中同樣也有這道題:Reverse a singly linked list

答案:http://www.programcreek.com/2014/05/leetcode-reverse-linked-list-java/

對於非遞歸的實現方法:使用三個臨時指針依次遍歷。

具體代碼如下:

1. 首先給出節點類

 1 class Node
 2 {
 3 public:
 4     Node(string curData,Node *mNext){
 5         data = curData;
 6         next = mNext;
 7     }
 8     ~Node(){
 9         cout<<data<<"析構函數"<<endl;
10     }
11 public:
12     string data;
13     Node *next;
14     
15 };

2. 非遞歸實現單鏈表倒序:

Node *listInvert(Node *head)
{
    Node *p1,*p2,*p3;
    p1 = head;
    p2 = p1->next;

    while(p2)
    {
        p3 = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = p3;
    }
    head->next = NULL;//注意:此時頭指針改變

    return p1;
}

3. 遞歸實現逆序:

//遞歸調用
Node * reverseRecursion(Node *head)
{
    if (head == NULL||head->next == NULL)
    {
        return head;
    }

    Node *second = head->next;
    head->next = NULL;

    Node *rest = reverseRecursion(second);

    second->next = head;

    return rest;
}

4. 方法調用:

void printNode(Node *root)
{
    while(root != NULL)
    {
        cout<<root->data<<" ";
        root = root->next;
    }
    cout<<endl;
}
int main(int argc, char const *argv[])
{
    Node *four = new Node("D",NULL);
    Node *third = new Node("C",four);
    Node *sec = new Node("B",third);
    Node *head = new Node("A",sec);
    
    // cout<<"原始鏈表順序:";
    // printNode(head);
    // Node *result = listInvert(head);
    // cout<<"倒序結果:";
    // printNode(result);

    cout<<"原始鏈表順序:";
    printNode(head);
    Node *result = reverseRecursion(head);
    cout<<"遞歸 倒序結果:";
    printNode(result);
    cout<<endl;


    delete head;
    delete sec;
    delete third;
    head = NULL;
    sec = NULL;
    third = NULL;
    return 0;
}

5. 結果

原始鏈表順序:A B C D 
遞歸 倒序結果:D C B A 

A析構函數
B析構函數
C析構函數

 6. 源碼 algorithm/list_invert.cpp


免責聲明!

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



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