92. Reverse Linked List II

Posted ArgenBarbie

tags:

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

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->NULLm = 2 and n = 4,

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

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if(!head || !head->next || m == n)
            return head;
        ListNode *left, *h, *t, *p, *q;
        ListNode fake(-1);
        fake.next = head;
        left = &fake;
        int i;
        for(i = 1; i < m; i++)
        {
            left = left->next;
        }
        h = left->next;
        t = h;
        p = h->next;
        for(i = m+1; i <= n; i++)
        {
            q = p->next;
            p->next = h;
            h = p;
            p = q;
        }
        left->next = h;
        t->next = p;
        return fake.next;
    }
};

注意要加fake头结点。

以上是关于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