Question: https://oj.leetcode.com/problems/partition-list/
Question Name: Partition List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Solution: # @param head, a ListNode # @param x, an integer # @return a ListNode def partition(self, head, x): smaller = ListNode(-1) # A pseudo head node to link all nodes, whose # value is less than x others = ListNode(-1) # A pseudo head node to link all nodes, whose # value is greater than or equal to x # Record the last nodes in "smaller" and "others" lists respectively. smallerLast, othersLast = smaller, others while head != None: if head.val < x: # Append to the end of "smaller" list smallerLast.next = head smallerLast = smallerLast.next else: # Append to the end of "others" list othersLast.next = head othersLast = othersLast.next head = head.next smallerLast.next = others.next # Append the "others" list to the end # of "smaller" othersLast.next = None # Close the whole list return smaller.next # Skip the pseudo head node. |