forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Partition_List.cpp
72 lines (66 loc) · 1.47 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
66
67
68
69
70
71
72
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 9, 2012
Problem: Partition List
Difficulty: medium
Source: http://www.leetcode.com/onlinejudge
Notes:
Given a linked list and a value x, partition it such that all nodes less than
x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the
two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
Solution:
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
ListNode *pre_head = NULL, *pre_tail = NULL;
ListNode *post_head = NULL, *post_tail = NULL;
while (head != NULL) {
if (head->val < x) {
if (pre_head == NULL) {
pre_head = head;
pre_tail = head;
} else {
pre_tail->next = head;
pre_tail = pre_tail->next;
}
} else {
if (post_head == NULL) {
post_head = head;
post_tail = head;
} else {
post_tail->next = head;
post_tail = post_tail->next;
}
}
head = head->next;
}
if (pre_head != NULL) {
pre_tail->next = post_head;
}
if (post_head != NULL) {
post_tail->next = NULL;
}
return (pre_head != NULL ? pre_head : post_head);
}
};