-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPartition List.cpp
More file actions
66 lines (61 loc) · 1.49 KB
/
Partition List.cpp
File metadata and controls
66 lines (61 loc) · 1.49 KB
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
/*
Platform :- Leetcode
Problem :- Partition List
Event :- April Daily challenge
*/
/**
* 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) {
vector<int>P,Q;
ListNode*temp=head;
while(temp){
if(temp->val<x){
P.push_back(temp->val);
}
else Q.push_back(temp->val);
temp=temp->next;
}
ListNode*ans=NULL;
temp=NULL;
//sort(P.begin(),P.end());
for(auto x:P){
if(!ans){
ListNode* y=new ListNode(x);
temp=y;
temp->next=NULL;
ans=temp;
}
else{
ListNode* y=new ListNode(x);
temp->next=y;
y->next=NULL;
temp=temp->next;
}
}
for(auto x:Q){
if(!ans){
ListNode* y=new ListNode(x);
temp=y;
temp->next=NULL;
ans=temp;
}
else{
ListNode* y=new ListNode(x);
temp->next=y;
y->next=NULL;
temp=temp->next;
}
}
return ans;
}
};