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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。(你应当保留两个分区中每个节点的初始相对位置。)
使用两个临时头节点,将大于X的保存在less_head,将大于等于X的保存于more_head,再把二者连接起来。
while head://这时head是遍历到链表的最后一个节点
while head and head.next://这时head遍历到链表的倒数第二个节点
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
less_head=less=ListNode(0)
more_head=more=ListNode(0)
while head:
if head.val < x:
less.next=head
less=less.next
else:
more.next=head
more=more.next
head=head.next
less.next=more_head.next
more.next=None
return less_head.next