鏈表反轉詳解


前言:

在上一篇博客實現鏈表的創建后,我們對其創建的鏈表進行反轉以及任意反轉。

分析:

假設我們對鏈表每三個節點進行一次反轉,有如下鏈表:

若對其反轉,則我們想要的結果為:

   

思路:

我們可以用頭插法的方式對其進行反轉,頭插法的方式:

一開始鏈表只有一個Head頭節點,現加入節點1

如果此時加入加入節點2那么節點2的next信息為Head頭的next信息,即2指向1,Head頭的next信息更新為節點2的地址

以此類推,當加入節點4時,我們應該把4接在節點1的后面,這時就應該移動鏈表的插入位置,在開始時插入位置為頭節點,加入節點4時插入位置為節點3,相當於

一個新的目標頭節點。

若要實現簡單的反轉,直接按照頭插法插入即可

實現代碼:

Node *ReverseList(Node *head) {
    Node *L = NULL, *tmp = NULL, *newH = NULL;
    int count = 0;
    L = (Node *)malloc(sizeof(Node) );
    L -> next = NULL;
    newH = L;
    head = head -> next;
    while(head != NULL) {
        ++count;                              // 對節點進行計數,
        tmp = (Node *)malloc(sizeof(Node) );  //  頭插法的實現
        tmp -> data = head -> data;           //
        tmp -> next = L -> next;              //  
        L->next = tmp;                        //
        head = head->next;
        if(count%3==0) while(L->next!=NULL) L = L -> next; // 移動頭節點
    }
    return newH;
}

 

完整代碼:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <queue>
#include <map>
#include <list>
#include <utility>
#include <set>
#include <algorithm>
#include <deque>
#include <vector>
#define mem(arr,num) memset(arr,0,sizeof(arr))
#define _for(i, a, b) for(int i = a; i <= b; i++)
#define __for(i, a, b) for(int i = a; i >=b; i--)
#define IO ios::sync_with_stdio(false);\
        cin.tie(0);\
        cout.tie(0);
using namespace std;
typedef long long ll;
typedef vector<int > vi;
const ll INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const int N = 5000 + 5;
typedef struct node {
    int data;
    struct node *next;
}Node;
Node *CreateList() {
    Node *L, *head, *tmp;
    int num;
    L = (Node *)malloc(sizeof(Node));
    L -> next = NULL;
    head = L;
    while(scanf("%d", &num) && num) {
        tmp = (Node *)malloc(sizeof(Node) );
        tmp -> data = num;
        tmp -> next = NULL;
        L -> next = tmp;
        L = tmp;
    }
    return head;
}
Node *ReverseList(Node *head) {
    Node *L = NULL, *tmp = NULL, *newH = NULL;
    int count = 0;
    L = (Node *)malloc(sizeof(Node) );
    L -> next = NULL;
    newH = L;
    head = head -> next;
    while(head != NULL) {
        ++count;                              // 對節點進行計數,
        tmp = (Node *)malloc(sizeof(Node) );  //  頭插法的實現
        tmp -> data = head -> data;           //
        tmp -> next = L -> next;              //  
        L->next = tmp;                        //
        head = head->next;
        if(count%3==0) while(L->next!=NULL) L = L -> next; // 移動頭節點
    }
    return newH;
}
void ReadList(Node *head) {
    head = head -> next;
    while(head != NULL) {
        printf("%d\n",head -> data);
        head = head -> next;
    }
}
int main() {
    Node *head = CreateList();
    Node *newH = ReverseList(head);
    ReadList(newH);
    return 0;
}


免責聲明!

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



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