-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (48 loc) · 1.26 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Title : partition-list
// Date : 2019-02-20
// Author : Daguo
/*****************************************
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
在
*****************************************/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* 思路:用两个节点分别开始两条链,一条放符合条件的,然后连起来
* @param {ListNode} head
* @param {number} x
* @return {ListNode}
*/
var partition = function(head, x) {
let h1 = { next: null };
let h2 = { next: null };
let s1 = h1;
let s2 = h2;
while (head) {
// 注意引用赋值的顺序
if (head.val < x) {
h1.next = head;
head = head.next;
h1 = h1.next;
h1.next = null;
} else {
h2.next = head;
head = head.next;
h2 = h2.next;
h2.next = null;
}
}
// 前面最后一个结点需要置null,不然会导致最后一位循环引用
h1.next = s2.next;
return s1.next;
};
module.exports = [partition];