题目描述
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
思路
设置两个子链表,其中一个放小于x的结点,最后将两个链表合并。
但是,要注意,将原链表结点加入到子链表中时,需要将该结点的next指针设置为None。
代码
class Solution(object):
def partition(self, head, x):
lef = ListNode()
rig = ListNode()
h1 = ListNode(next=lef)
h2 = ListNode(next=rig)
while head != None:
if head.val < x:
lef.next = head
head = head.next
lef = lef.next
lef.next = None
else:
rig.next = head
head = head.next
rig = rig.next
rig.next = None
lef.next = h2.next.next
return h1.next.next