PU Reverse Linked List II

Jan 01, 1970

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

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

For example:

  • Given 1->2->3->4->5->NULL, m = 2 and n = 4,
  • return 1->4->3->2->5->NULL.

C Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
    struct ListNode dummy, *p = &dummy;
    p->next = head;
    n -= m;
    while (--m) p = p->next;
    head = p->next;
    while (n--) {
       struct ListNode *tmp = head->next;
       head->next = tmp->next;
       tmp->next = p->next;
       p->next = tmp;
    }
    return dummy.next;
}

Python Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode(0)
        dummy.next = head
        head = dummy
        for _ in range(m - 1):
            head = head.next
        cur = head.next
        for _ in range(n - m):
            tmp = cur.next
            head.next, cur.next, tmp.next = tmp, tmp.next, head.next
        return dummy.next

Summary:

  1. 3ms, 1.3%
  2. n-- is used base on 1 <= m <= n <= length of list.
  3. Dummy is necessary because the head may be reversed.

LeetCode: 92. Reverse Linked List II