【leetcode-86】 分隔链表

时间:2023-03-09 03:28:53
【leetcode-86】 分隔链表

(1过)

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5 思路两个链表拼接
最初做时犯了个错误,加入新链表后没有与原链表断开,导致超时错误
    public ListNode partition(ListNode head, int x) {
// 头指针
ListNode smaller = new ListNode(0);
ListNode bigger = new ListNode(0);
ListNode curSmaller = smaller;
ListNode curBigger = bigger;
while(head != null) {
if (head.val < x){
curSmaller.next = head;
head = head.next;
curSmaller = curSmaller.next;
// 加入新链表后要与原链表断开
curSmaller.next = null;
} else {
curBigger.next = head;
head = head.next;
curBigger = curBigger.next;
curBigger.next = null;
}
}
curSmaller.next = bigger.next;
return smaller.next;
}