leetcode86 Partition List-zh
# 86. 分隔链表 (opens new window)
English Version (opens new window)
# 题目描述
给你一个链表的头节点 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 <= Node.val <= 100
-200 <= x <= 200
# 解法
创建两个链表,一个存放小于 x
的节点,另一个存放大于等于 x
的节点,之后进行拼接即可。
# Python3
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
l1, l2 = ListNode(), ListNode()
cur1, cur2 = l1, l2
while head:
if head.val < x:
cur1.next = head
cur1 = cur1.next
else:
cur2.next = head
cur2 = cur2.next
head = head.next
cur1.next = l2.next
cur2.next = None
return l1.next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode l1 = new ListNode(0);
ListNode l2 = new ListNode(0);
ListNode cur1 = l1, cur2 = l2;
while (head != null) {
if (head.val < x) {
cur1.next = head;
cur1 = cur1.next;
} else {
cur2.next = head;
cur2 = cur2.next;
}
head = head.next;
}
cur1.next = l2.next;
cur2.next = null;
return l1.next;
}
}
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
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
# C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* l1 = new ListNode();
ListNode* l2 = new ListNode();
ListNode* cur1 = l1;
ListNode* cur2 = l2;
while (head != nullptr) {
if (head->val < x) {
cur1->next = head;
cur1 = cur1->next;
} else {
cur2->next = head;
cur2 = cur2->next;
}
head = head->next;
}
cur1->next = l2->next;
cur2->next = nullptr;
return l1->next;
}
};
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
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
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38