-
Notifications
You must be signed in to change notification settings - Fork 1
/
partition_linked_list_x.cpp
90 lines (84 loc) · 1.24 KB
/
partition_linked_list_x.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<iostream>
using namespace std;
typedef struct node node;
struct node {
int value;
node* next;
};
class list {
node* head;
public:
list(){
this->head = NULL;
}
void insert(int n){
if(this->head == NULL){
this->head = new node;
this->head->value = n;
this->head->next = NULL;
}
else{
node* p = this->head;
while(p->next!=NULL)
p = p->next;
p->next = new node;
p = p->next;
p->value = n;
p->next = NULL;
}
}
node* partition_list(int x){
node *lhead = NULL, *hhead = NULL, *p = this->head, *lp = NULL, *hp = NULL;
while(p != NULL){
if(p->value < x){
if(lp == NULL){
lhead = p;
lp = p;
}
else{
lp = lp->next;
}
p = p->next;
}
else{
if(hp == NULL){
hhead = p;
hp = p;
}
else{
hp->next = p;
hp = hp->next;
}
lp->next = p->next;
p->next = NULL;
p = lp->next;
}
}
lp->next = hhead;
return this->head;
}
void print(){
node* p = this->head;
while(p != NULL){
cout << p->value << " ";
p = p->next;
}
cout << endl;
}
};
int main()
{
list l;
int n, e;
cin >> n;
for(int i=0; i<n; i++){
cin >> e;
l.insert(e);
}
int x;
cin >> x;
l.print();
l.partition_list(x);
l.print();
return 0;
}