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.

 

cpp:

class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode *Head = new ListNode(-1);
        Head->next = head;
        ListNode *tail1 = Head;
        for(int i=1;i<m;i++){
            tail1 = head;
            head = head->next;
        }
        ListNode *mNode = tail1->next;

        ListNode* cur = nullptr;
        for(int i=m;i<=n;i++){
            cur = head;
            head = cur->next;
            cur->next = tail1->next;
            tail1->next= cur;
        }

        if(cur->next!= nullptr){
            mNode->next = head;
        }

        return Head->next;
    }
};

 

posted @ 2016-02-27 23:08  wxquare  阅读(150)  评论(0编辑  收藏  举报