且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Reverse Linked List II

更新时间:2022-01-14 23:33:05

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

解题思路

解题思路与上一篇Reverse Linked List类似,只不过这里是反转部分链表。
因此,只需将m到n部分翻转,然后将m的前缀beforeM指向该部分反转后的头结点即可。如果beforeM为NULL,则m=1,m到n部分的头结点即为链表的头结点。

实现代码

//Runtime: 4 ms
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;

struct ListNode{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode *cur = head;
        ListNode *beforeM = NULL;
        for (int i = 1; i < m; i++)
        {
            beforeM = cur;
            cur = cur->next;
        }

        ListNode *localhead = cur;
        ListNode *pre = cur;
        cur = cur->next;
        int count = n - m;
        while (count--)
        {
            pre->next = cur->next;
            cur->next = localhead;
            localhead = cur;
            cur = pre->next;
        }

        if (beforeM == NULL)
        {
            head = localhead;
        }
        else
        {
            beforeM->next = localhead;
        }

        return head;
    }
};

void printList(ListNode *head)
{
    while(head != NULL)
    {
        cout<<head->val<<" ";
        head = head->next;
    }
    cout<<endl;
}

void dropList(ListNode *head)
{
    if (head == NULL) return;
    ListNode *temp;
    while (head != NULL)
    {
        temp = head->next;
        delete head;
        head = temp;
    }
}

int main()
{
    ListNode *head = new ListNode(0);
    ListNode *cur = head;
    for (int i = 0; i < 10; i++)
    {
        ListNode *newnode = new ListNode(floor(rand()%77));
        cur->next = newnode;
        cur = newnode;
    }
    printList(head);
    Solution s;
    head = s.reverseBetween(head, 2, 5);
    printList(head);
    dropList(head);
}