86. 分隔链表
Difficulty: 中等
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
Solution
如果没有second.next = None
这一行代码,新得出的链表中将会有一个环,比如根据下面给出的解法,first
是1->2->2,second
是4->3->5,此时second中的5节点仍然还是指向2(也就是first中的最后一个节点),然后first.next = high.next
,此时链表中就存在一个环了。所以需要使得second链表的最后一个节点指向None。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
if not head: return None
low, high = ListNode(-1), ListNode(-1)
first, second = low, high
while head:
if head.val < x:
first.next = head
first = first.next
else:
second.next = head
second = second.next
head = head.next
second.next = None
first.next = high.next
return low.next