手撕链表题

发布时间 2023-09-05 19:51:14作者: SuperTonyy

第一题,实现链表翻转

第二题,实现链表指定区域翻转

#include <bits/stdc++.h>
using namespace std;
struct ListNode {
    int val;
    struct ListNode* next;
    ListNode(int x) : val(x), next(nullptr){}
};
ListNode* ReverseList(ListNode* head) {   //第一题 翻转链表
    ListNode* pre = nullptr;
    ListNode* cur = head;
    ListNode* nex = nullptr;
    while (cur) {
        nex = cur->next;
        cur->next = pre;
        pre = cur;
        cur = nex;
    }
    return pre;
}
ListNode* reverseBetween(ListNode* head, int m, int n) { //第二题 翻转链表指定区间[m,n]
    ListNode* ans = new ListNode(-1);
    ans->next = head;
    ListNode* pre = ans;
    ListNode* cur = head;
    ListNode* nex = nullptr;
    for (int i = 1;i < m;i++) {
        pre = cur;
        cur = cur->next;
    }
    for (int i = m;i < n;i++) {
        nex = cur->next;
        cur->next = nex->next;
        nex->next = pre->next;
        pre->next = nex;
    }
    return ans->next;
}
int main()
{
    ListNode* l1 = new ListNode(1);
    ListNode* l2 = new ListNode(2);
    ListNode* l3 = new ListNode(3);
    ListNode* l4 = new ListNode(4);
    l1->next = l2;
    l2->next = l3;
    l3->next = l4;
    ListNode* ans = reverseBetween(l1,2,4);
    while (ans) {
        cout << ans->val << " ";
        ans = ans->next;
    }

    return 0;
}