LeetCode Reverse Linked List II
Reverse Linked List II
Original question
When only one traversal is performed and no additional space is requested, the elements m to n in a linked list are flipped over.
Note:
M and n meet the following conditions: 1 ≤ m ≤ n ≤ length of the linked list
Example:
Input: 1-> 2-> 3-> 4-> 5-> NULL, m = 2, n = 4
Output: 1-> 4-> 3-> 2-> 5-> NULL
Solutions
You can use the Reverse Linked List to flip the Linked List. Look, you can flip a section first, and then connect it to the front and back linked list. Because the first node may have to be flipped over, a false header node is added for consistency.
AC Source Code
# Definition for singly-linked list.class ListNode(object): def __init__(self, x): self.val = x self.next = None def to_list(self): return [self.val] + self.next.to_list() if self.next else [self.val]class Solution(object): def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head node = dummy for __ in range(m - 1): node = node.next prev = node.next curr = prev.next for __ in range(n - m): next = curr.next curr.next = prev prev = curr curr = next node.next.next = curr node.next = prev return dummy.nextif __name__ == "__main__": n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n5 = ListNode(5) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 r = Solution().reverseBetween(n1, 2, 4) assert r.to_list() == [1, 4, 3, 2, 5]