LeetCode Partition List
Partition List for solving LeetCode Problems
Original question
Given a linked list and a target value, all nodes smaller than the target value are moved to the front end of the linked list, and nodes larger than or equal to the target value are moved to the end of the linked list, at the same time, we need to maintain the relative position of the two parts in the original linked list.
Note:
Sort the linked list by reconnecting the pointer.
Example:
Input: head = 1-> 4-> 3-> 2-> 5-> 2, x = 3
Output: 1-> 2-> 2-> 4-> 3-> 5
Solutions
We can see a beaded with red and blue colors. Now we need to combine red and blue. You can traverse each bead. If it is blue, it will be stringed on one line, and the red string will be placed on another line. Then you can connect the two lines. Note: In the large string number, the final pointer should be set to None, because it is the last node after sorting.
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 partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head small_dummy = ListNode(-1) large_dummy = ListNode(-1) prev = dummy small_prev = small_dummy large_prev = large_dummy while prev.next: curr = prev.next if curr.val < x: small_prev.next = curr small_prev = small_prev.next else: large_prev.next = curr large_prev = large_prev.next prev = prev.next large_prev.next = None small_prev.next = large_dummy.next return small_dummy.nextif __name__ == "__main__": n1 = ListNode(1) n2 = ListNode(4) n3 = ListNode(3) n4 = ListNode(2) n5 = ListNode(5) n6 = ListNode(2) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n6 r = Solution().partition(n1, 3) assert r.to_list() == [1, 2, 2, 4, 3, 5]