1. 程式人生 > >資料結構篇:單鏈表倒置(帶頭結點/不帶頭結點)

資料結構篇:單鏈表倒置(帶頭結點/不帶頭結點)

帶頭結點

初始化如圖

1.我們需要把1這個結點作為最後一個結點,所以要把1的next指向NULL

h->next->next = nullptr;

 

2.然後我們要新建結點,指向HeadNext的下一位,並把HeadNext的下一位指向HeadPre,

Inode *tempNode = HeadNext->next;
HeadNext->next = HeadPre;

 

3. HeadPre指向HeadNext為下一次迴圈做準備

HeadPre = HeadNext;

 4.如果tempNode為空,說明HeadNext已經是最後一個結點,把頭結點的下一位指向HeadNext

if (tempNode == nullptr)
{
    h->next = HeadPre;
}

5.將HeadNext往後移一位 

HeadNext = tempNode;

 

6.繼續迴圈,直至HeadNext為空

完整函式

Inode *Test::ReserveLink(Inode *h) {
    Inode *HeadNext, *HeadPre;
    HeadNext = h->next->next;
    HeadPre = h->next;
    h->next->next = nullptr;
    while (HeadNext)
    {
        Inode *tempNode = HeadNext->next;
        HeadNext->next = HeadPre;
        HeadPre = HeadNext;
        if (tempNode == nullptr)
        {
            h->next = HeadPre;
        }
        HeadNext = tempNode;
    }
    return h;
}

執行截圖

完整程式

#include <iostream>

using namespace std;

typedef struct Link {
    int num;
    Link *next;
} Inode;

class Test {
public :
    Inode *t_CreateList(Inode *Head, int n);//尾插法建立單鏈表
    void ShowLink(Inode *h);

    Inode *ReserveLink(Inode *h);
};

Inode *Test::t_CreateList(Inode *Head, int n) {
    Inode *p = Head;
    for (int i = 0; i < n; i++)
    {
        Inode *s = new Inode;
        cin >> s->num;
        s->next = p->next;
        p->next = s;
        p = s;
    }
    return Head;
}


void Test::ShowLink(Inode *h) {
    Inode *p = h;
    cout<<"單鏈表為:"<<endl;
    while (p->next)
    {
        cout << p->next->num <<"-->";
        p = p->next;
    }
    cout<<endl;
}

Inode *Test::ReserveLink(Inode *h) {
    Inode *HeadNext, *HeadPre;
    HeadNext = h->next->next;
    HeadPre = h->next;
    h->next->next = nullptr;
    while (HeadNext)
    {
        Inode *tempNode = HeadNext->next;
        HeadNext->next = HeadPre;
        HeadPre = HeadNext;
        if (tempNode == nullptr)
        {
            h->next = HeadPre;
        }
        HeadNext = tempNode;
    }
    return h;
}

int main() {
    Test test;
    Inode *Head = new Inode;
    Head->next = NULL;
    int num;
    cout << "您想要建立幾個元素的單鏈表?請輸入:" << endl;
    cin >> num;
    Head = test.t_CreateList(Head, num);
    test.ShowLink(Head);
    Head = test.ReserveLink(Head);
    test.ShowLink(Head);
    return 0;
}

不含頭結點

Inode *Test::ReserveLink(Inode *h) {
    Inode *HeadNext, *HeadPre;
    HeadNext = h->next;
    HeadPre = h;
    h->next = nullptr;
    while (HeadNext)
    {
        Inode *tempNode = HeadNext->next;
        HeadNext->next = HeadPre;
        HeadPre = HeadNext;
        if (tempNode == nullptr)
        {
            h = HeadPre;
        }
        HeadNext = tempNode;
    }
    return h;
}