leetcode[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) 

{

    ListNode *newh=new ListNode(0);

    newh->next=head;

    ListNode *p=newh;

    ListNode *pre=newh, *left, *right, *after;

    int i=0;

    while (p&&i<m)

    {

        pre=p;

        p=p->next;

        left=p;

        right=left;

        i++;

    }

    p=p->next;

    after=p;

    for (i=m;i<n;i++)

    {

        p=p->next;

        right->next=after->next;

        pre->next=after;

        after->next=left;

        left=after;

        after=p;

    }

    return newh->next;

}

/*

ListNode *reverseBetween(ListNode *head, int m, int n) 

{

    ListNode *newh=new ListNode(0);

    newh->next=head;

    ListNode *p=newh->next;

    int i=1;

    vector<ListNode *> vec;

    while(p&&i<=n)

    {

        if(i>=m&&i<=n)

        {

            vec.push_back(p);

        }

        i++;

        p=p->next;

    }

    for (int j=0;j<(n-m+1)/2;j++)

    {

        int tmp=vec[j]->val;

        vec[j]->val=vec[(n-m)-j]->val;

        vec[(n-m)-j]->val=tmp;

    }

    return newh->next;

}

*/

};

 

你可能感兴趣的:(LeetCode)