[leetcode] 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->NULL, m = 2 and n = 4,

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

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

tag: linked-list

可以套用第一版Reserve Linked List的部分代码。

先找到要反转的node们的前一个node–prev;

然后标记要反转的第一个node–start;

一个一个反转node,直到到结尾。然后拼接node,done。

/**
 * 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 * superHead = new ListNode(0);
        ListNode * prev = superHead;
        superHead->next = head;
        for(int i = 1; i < m; i++){
            prev = prev->next;
        }
        //reverse linked list
        ListNode *  start = prev->next;
        ListNode * p, *q, *r;
        p = start;
        q = p->next;
        for(int i = m; i < n; i++){
            r = q->next;
            q->next = p;
            p = q;
            q = r;
        }
        //p is tail of reserved list, q is the start of unreserved list
        prev->next = p;
        start->next = q;
        head = superHead->next;
        delete superHead;
        return head;
    }
};

 

Untitled

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.