Skip to content

Commit bc1e67d

Browse files
committed
📝 add lc 86
1 parent 4439576 commit bc1e67d

File tree

2 files changed

+103
-0
lines changed

2 files changed

+103
-0
lines changed

Java/alg/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@
128128
- [78.子集](lc/78.子集.md)
129129
- [79.单词搜索](lc/79.单词搜索.md)
130130
- [82.删除排序链表中的重复元素2](lc/82.删除排序链表中的重复元素2.md)
131+
- [86.分隔链表](lc/86.分隔链表.md)
131132

132133
## 笔试
133134

Java/alg/lc/86.分隔链表.md

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# 86. 分隔链表
2+
3+
[url](https://leetcode-cn.com/problems/partition-list/))
4+
5+
## 题目
6+
7+
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
8+
9+
你应当 保留 两个分区中每个节点的初始相对位置。
10+
11+
![](https://assets.leetcode.com/uploads/2021/01/04/partition.jpg)
12+
13+
```
14+
输入:head = [1,4,3,2,5,2], x = 3
15+
输出:[1,2,2,4,3,5]
16+
输入:head = [2,1], x = 2
17+
输出:[1,2]
18+
```
19+
20+
## 方法
21+
22+
23+
## code
24+
25+
### js
26+
27+
```js
28+
let partition = (head, x) => {
29+
let dummy1, dummy2 = new ListNode(0);
30+
let node1 = dummy1, node2 = dummy2;
31+
while (head !== null) {
32+
if (head.val < x) {
33+
node1.next = head;
34+
head = head.next;
35+
node1 = node1.next;
36+
node1.next = null;
37+
} else {
38+
node2.next = head;
39+
head = head.next;
40+
node2 = node2.next;
41+
node2.next = null;
42+
}
43+
}
44+
node1.nex = dummy2.next;
45+
return dummy1.next;
46+
}
47+
```
48+
49+
### go
50+
51+
```go
52+
func partition(head *ListNode, x int) *ListNode {
53+
if head == nil {return nil}
54+
dummy1, dummy2 := &ListNode{}, &ListNode{}
55+
cur1, cur2 := dummy1, dummy2
56+
for head != nil {
57+
if head.Val < x {
58+
cur1.Next = head
59+
head = head.Next
60+
cur1 = cur1.Next
61+
cur1.Next = nil
62+
} else {
63+
cur2.Next = head
64+
head = head.Next
65+
cur2 = cur2.Next
66+
cur2.Next = nil
67+
}
68+
}
69+
cur1.Next = dummy2.Next
70+
return dummy1.Next
71+
}
72+
```
73+
74+
75+
76+
### java
77+
78+
```java
79+
class Solution {
80+
public ListNode partition(ListNode head, int x) {
81+
ListNode dummy1 = new ListNode(0);
82+
ListNode dummy2 = new ListNode(0);
83+
ListNode node1 = dummy1, node2 = dummy2;
84+
while (head != null) {
85+
if (head.val < x){
86+
node1.next = head;
87+
head = head.next;
88+
node1 = node1.next;
89+
node1.next = null;
90+
} else {
91+
node2.next = head;
92+
head = head.next;
93+
node2 = node2.next;
94+
node2.next = null;
95+
}
96+
}
97+
node1.next = dummy2.next;
98+
return dummy1.next;
99+
}
100+
}
101+
```
102+

0 commit comments

Comments
 (0)