Open Ray-56 opened 4 years ago
var partition = function(head, x) {
let beforeHead = new ListNode();
let afterHead = new ListNode();
let before = beforeHead;
let after = afterHead;
let cur = head;
while (cur) {
if (cur.val < x) {
before.next = cur;
before = before.next;
} else {
after.next = cur;
after = after.next;
}
cur = cur.next;
}
after.next = null;
before.next = afterHead.next;
return beforeHead.next;
};
86. 分隔链表
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例: