Skip to content

Commit 68ee9ba

Browse files
committed
two pointers is not that easy
1 parent 497d426 commit 68ee9ba

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

86. Partition List/Solution.cpp

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#include <string>
2+
#include <vector>
3+
#include <iostream>
4+
#include <sstream>
5+
#include <algorithm>
6+
using namespace std;
7+
8+
// Definition for singly-linked list.
9+
struct ListNode {
10+
int val;
11+
ListNode *next;
12+
ListNode(int x) : val(x), next(NULL) {}
13+
};
14+
15+
class Solution {
16+
public:
17+
ListNode* partition(ListNode* head, int x) {
18+
if (head == NULL) return head;
19+
ListNode * header = new ListNode(0);
20+
header->next = head;
21+
auto p1 = header, p2 = header; // p1, p2 not NULL
22+
// p1 -> the last number < x, p2 -> cur
23+
while (p2 != NULL and p2->next != NULL) { // see the next node value
24+
if (p2->next->val < x) {
25+
if ( p1 == p2 ) {
26+
p1 = p1->next;
27+
p2 = p2->next;
28+
continue;
29+
}
30+
// swap
31+
auto p3 = p2->next, p4 = p3->next;
32+
auto p1n = p1->next;
33+
p1->next = p3;
34+
p3->next = p1n;
35+
p2->next = p4;
36+
p1 = p1->next;
37+
} else
38+
p2 = p2->next;
39+
}
40+
return header->next;
41+
}
42+
};
43+
44+
int main() {
45+
Solution s;
46+
ListNode a(1);
47+
ListNode b(4);
48+
ListNode c(3);
49+
ListNode d(2);
50+
ListNode e(5);
51+
ListNode f(2);
52+
a.next = &b;
53+
b.next = &c;
54+
c.next = &d;
55+
d.next = &e;
56+
e.next = &f;
57+
auto x = s.partition(&a,3);
58+
while (x != NULL) {
59+
cout << x->val << endl;
60+
x = x->next;
61+
}
62+
return 0;
63+
}

0 commit comments

Comments
 (0)