【LeetCode】92. Reverse Linked List II

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.

 

把[m,n]那一段抠出来,reverse之后,再拼回去。

需要注意的是,reverse函数的参数需要是指针引用*&。

附:指针传递与指针引用传递的区别

当我们把指针做为参数传递时,其实是把指针的副本传递给了函数,也可以说传递指针是指针的值传递。这样当我们在函数内部修改指针时,在函数里修改只是修改的指针的副本,而不是指针本身,原来的指针还保留着原来的值。

 

/**
 * 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 == NULL)
            return head;

        ListNode *newhead = new ListNode(-1);
        newhead->next = head;

        ListNode *prebegin = newhead;
        ListNode *begin = head;

        ListNode *end = newhead;
        ListNode *postend = head;

        while(--m)
        {
            prebegin = prebegin->next;
            begin = begin->next;
        }
        while(n--)
        {
            end = end->next;
            postend = postend->next;
        }
        //reverse
        reverse(begin, end);
        //link
        prebegin->next = begin;
        end->next = postend;

        return newhead->next;
    }
    void reverse(ListNode*& begin, ListNode*& end)
    {
        if(begin == end)
            return;
        else if(begin->next == end)
            end->next = begin;
        else
        {//at least 3 nodes
            ListNode* pre = begin;
            ListNode* cur = pre->next;
            ListNode* post = cur->next;
            while(post != end->next)
            {
                cur->next = pre;
                pre = cur;
                cur = post;
                post = post->next;
            }
            cur->next = pre;
        }
        //swap
        ListNode* temp = begin;
        begin = end;
        end = temp;
    }
};

你可能感兴趣的:(LeetCode)