Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
基本的思路是把 小于x 的部分和 大于等于x 的部分用两个list来表示,之后再把两个list连在一起。例如:dummy1 为head的list为小于x的nodes,dummy2的则为大于等于x的nodes.
class Solution:
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
dummy1 = ListNode(0) # smaller than x
dummy2 = ListNode(0) # equal or larger than x
curr1 = dummy1
curr2 = dummy2
curr = head
while curr:
if curr.val < x:
curr1.next = curr
curr = curr.next
curr1 = curr1.next
curr1.next = None
else:
curr2.next = curr
curr = curr.next
curr2 = curr2.next
curr2.next = None
curr1.next = dummy2.next
return dummy1.next