给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
示例 1:
输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2
输出:[1,2]
提示:
- 链表中节点的数目在范围 [0, 200] 内
- -100 <= Node.val <= 100
- -200 <= x <= 200
解题:
func partition(head *ListNode, x int) *ListNode {
r := &ListNode{0, nil}
n := &ListNode{0, nil}
start, other := r, n
for head != nil {
if head.Val < x {
other.Next = head
head = head.Next
other.Next.Next = nil
other = other.Next
} else {
start.Next = head
head = head.Next
start.Next.Next = nil
start = start.Next
}
}
other.Next = r.Next
return n.Next
}
官方解答:
1.模拟
func partition(head *ListNode, x int) *ListNode {
small := &ListNode{}
smallHead := small
large := &ListNode{}
largeHead := large
for head != nil {
if head.Val < x {
small.Next = head
small = small.Next
} else {
large.Next = head
large = large.Next
}
head = head.Next
}
large.Next = nil
small.Next = largeHead.Next
return smallHead.Next
}