Leetcode 86. Partition List

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Partition List

2. Solution

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if(!head) {
return head;
}
ListNode* left_head = nullptr;
ListNode* right_head = nullptr;
ListNode* left = nullptr;
ListNode* right = nullptr;
ListNode* current = head;
while(current) {
if(current->val < x) {
if(left) {
left->next = current;
left = left->next;
}
else {
left = current;
left_head = left;
}
}
else {
if(right) {
right->next = current;
right = right->next;
}
else {
right = current;
right_head = right;
}
}
current = current->next;
}
if(right) {
right->next = nullptr;
}
if(left) {
left->next = right_head;
return left_head;
}
else {
return right_head;
}
}
};

Reference

  1. https://leetcode.com/problems/partition-list/description/
如果有收获,可以请我喝杯咖啡!