92. Reverse Linked List II

Posted dysjtu1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了92. Reverse Linked List II相关的知识,希望对你有一定的参考价值。

Problem:

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

Note: 1 ≤ mn ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

思路

保存2个节点precur,其中pre指向第m-1个节点(从1开始算),而cur指向第m个节点。在每次循环中,cur->next指向的节点插入到prepre->next指向的节点中,然后经过操作cur->next = cur->next->nextcur->next指向的节点右移一位,经过n-m次操作后cur->next指向第n+1个节点,然后经过n-m次插入操作后原本m后面的节点m+1到n节点倒序排列在m-1和m(现在的第n节点)节点之间。

Solution (C++):

ListNode* reverseBetween(ListNode* head, int m, int n) {
    ListNode *dummy = new ListNode(0), *pre = dummy, *cur;
    dummy->next = head;
    for (int i = 0; i < m - 1; ++i) {
        pre = pre->next;
    }
    cur = pre->next;    //pre指向第m-1个节点,cur指向第m个节点
    for (int i = 0; i < n - m; ++i) {       //每次循环时把第m+i+1个节点插入到(重新排列之后的)第m-1个节点和第m个节点之间
        ListNode *tmp = pre->next;
        pre->next = cur->next;
        cur->next = cur->next->next;
        pre->next->next = tmp;
    }
    return dummy->next;
}

性能

Runtime: 4 ms??Memory Usage: 8.9 MB

以上是关于92. Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章

92. Reverse Linked List II

92. Reverse Linked List II

92. Reverse Linked List II

#Leetcode# 92. Reverse Linked List II

LeetCode 92. Reverse Linked List II

92. Reverse Linked List II