[LeetCode] 92. Reverse Linked List II

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

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

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

/**
 * 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) {
        // 建一个dummy node,连上原链表的头结点,这样的话就算头结点变动了,还可以通过dummy->next来获得新链表的头结点
        ListNode *dummy = new ListNode(-1), *pre = dummy;
        dummy->next = head;
        
        ListNode* cur = nullptr;
        for (int i = 0; i < m - 1; i++) {
            pre = pre -> next;
        }
        cur =  pre -> next;
        
        for (int i = m; i < n; i++) {
            ListNode *t = cur->next;
            cur -> next = t -> next;
            // 注意此处 pre 指针是不会变化的
            t -> next = pre -> next;
            pre -> next = t;
        }
        return dummy->next;
    }
};

 

posted @ 2019-08-06 22:53  爱简单的Paul  阅读(122)  评论(0编辑  收藏  举报