题目:
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
思路:
建立两个索引,分块存储,然后连接
代码:
class Solution(object):
def partition(self, head, x):
sH = None
sT = None
bH = None
bT = None
while head != None:
nex = head.next
head.next = None
if head.val < x:
if sH == None:
sH = head
sT = head
else:
sT.next = head
sT = head
else:
if bH == None:
bH = head
bT = head
else:
bT.next = head
bT = head
head = nex
if sT != None:
sT.next =bH
if sH != None:
head = sH
else:
head = bH
return head