-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPartition List.cpp
66 lines (59 loc) · 1.35 KB
/
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
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void print_array(ListNode* head){
while(head!=NULL){
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
ListNode* head_small=NULL, *tail_small=NULL;
ListNode* head_big=NULL, *tail_big=NULL;
while(head!=NULL){
if(head->val<x){
if(head_small==NULL){
head_small=head;
tail_small = head_small;
}
else{
tail_small->next = head;
tail_small = tail_small->next;
}
}
else{
if(head_big==NULL){
head_big=head;
tail_big = head_big;
}
else{
tail_big->next = head;
tail_big = tail_big->next;
}
}
head = head->next;
}
if(head_small!=NULL)
tail_small->next = head_big;
else
return head_big;
if(tail_big!=NULL)
tail_big->next = NULL;
return head_small;
}
};
int main(){
Solution s = Solution();
ListNode* head = new ListNode(1);
head->next = new ListNode(4);
head->next->next = new ListNode(3);
head = s.partition(head,4);
print_array(head);
}