链表逆置算法 C++实现

链表逆置算法 C++实现

链表结构:

#include <iostream>
using namespace std;

 // Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
  1. 整个链表逆置:
    用一个新的空头指针,从第一个节点开始逐一接入新的头指针,新接入的节点的next为上一个接入节点的地址,以实现原地逆序
    代码:
// 核心算法写在一个类里
class Solution {
public:
	ListNode* reverseList(ListNode* head) {
        ListNode* new_head = NULL;
        ListNode* next = NULL;
        while (head) {
            next = head->next;
            head->next = new_head;
            new_head = head;
            head = next;
        }
        return new_head;
	}
};

// 测试
int main() {
    ListNode a(1);
    ListNode b(2);
    ListNode c(3);
    ListNode d(4);
    ListNode e(5);
    a.next = &b;
    b.next = &c;
    c.next = &d;
    d.next = &e;
    Solution solve;
    ListNode* head = &a, * p = head;
    cout << "矩阵逆置前:" << endl;
    while (p)
    {
        cout << p->val << endl;
        p = p->next;
    }
    head = solve.reverseList(head);
    p = head;
    cout << "矩阵逆置后:" << endl;
    while (p) {
        cout << p->val << endl;
        p = p->next;
    }
    return 0;
}

结果:

矩阵逆置前:
1
2
3
4
5
矩阵逆置后:
5
4
3
2
1
  1. 将链表从m至n逆序
    找到逆置的链表段的第一个节点及其前驱节点,再按上面的链表逆置方法逆置链表段,再进行整体连接
    代码:
// 核心算法写在一个类里
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        int change_len = n - m + 1; // 需要逆置的节点个数
        ListNode* pre_head = NULL;
        ListNode* result = head;
        while (head && --m) {
            pre_head = head; // 需要逆置的链表段的前驱节点
            head = head->next;
        }
        ListNode* modify_list_tail = head; // 当前的head,即逆置后的那一段链表的尾部
        ListNode* new_head = NULL;
        ListNode* next = NULL;
        while (head && change_len) {
            next = head->next;
            head->next = new_head;
            new_head = head;
            head = next;
            change_len--;
        }
        modify_list_tail->next = head;
        if (pre_head)
        {
            pre_head->next = new_head;
        }
        else
        {
            result = new_head;
        }
        return result;
    }
};

// 以下为测试
int main() {
    ListNode a(1);
    ListNode b(2);
    ListNode c(3);
    ListNode d(4);
    ListNode e(5);
    a.next = &b;
    b.next = &c;
    c.next = &d;
    d.next = &e;
    Solution solve;
    ListNode* head = &a, * p = head;
    cout << "矩阵逆置前:" << endl;
    while (p)
    {
        cout << p->val << endl;
        p = p->next;
    }
    head = solve.reverseBetween(head, 2, 4);
    p = head;
    cout << "矩阵逆置后:" << endl;
    while (p) {
        cout << p->val << endl;
        p = p->next;
    }
    return 0;
}

结果:

矩阵逆置前:
1
2
3
4
5
矩阵逆置后:
1
4
3
2
5

ps: 教程 https://www.bilibili.com/video/BV1GW411Q77S?t=7029&p=2 的笔记
LeetCode题号: 206,92

猜你喜欢

转载自blog.csdn.net/weixin_44427114/article/details/107765974