-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path86.ts
90 lines (85 loc) · 1.82 KB
/
86.ts
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* @lc app=leetcode.cn id=86 lang=typescript
*
* [86] 分隔链表
*
* https://leetcode.cn/problems/partition-list/description/
*
* algorithms
* Medium (65.06%)
* Likes: 854
* Dislikes: 0
* Total Accepted: 304.8K
* Total Submissions: 468.4K
* Testcase Example: '[1,4,3,2,5,2]\n3'
*
* 给你一个链表的头节点 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
* -200
*
*
*/
import {ListNode, travelList, makeList} from './labuladong/list'
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function partition(head: ListNode | null, x: number): ListNode | null {
// 边界条件
if (!head) return null
let dummy1 = new ListNode(-1001)
let p1 = dummy1
let dummy2 = new ListNode(-1002)
let p2 = dummy2
while (head) {
if (head.val < x) {
p1.next = head
p1 = p1.next
} else {
p2.next = head
p2 = p2.next
}
head = head.next
}
// 要注意在里需要把链表断开
p2.next = null
// 链接两条链表
p1.next = dummy2.next
// 返回第一条的头部
return dummy1.next
};
// @lc code=end
console.log(travelList(partition(makeList([1,4,3,2,5,2]),3)))