-
Notifications
You must be signed in to change notification settings - Fork 0
/
86.partition-list.cpp
57 lines (56 loc) · 1.27 KB
/
86.partition-list.cpp
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
#include <bits/stdc++.h>
using namespace std;
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) {}
};
/*
* @lc app=leetcode id=86 lang=cpp
*
* [86] Partition List
*/
// @lc code=start
/**
* 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 *dummy1 = new ListNode(0);
ListNode *dummy2 = new ListNode(0);
ListNode *p1 = dummy1, *p2 = dummy2;
ListNode *p = head;
while (p != nullptr)
{
if (p->val >= x)
{
p2->next = p;
p2 = p2->next;
}
else
{
p1->next = p;
p1 = p1->next;
}
ListNode *tmp = p->next;
p->next = nullptr;
p = tmp;
}
p1->next = dummy2->next;
return dummy1->next;
}
};
// @lc code=end