blob: 0deceb83625c02e4959430ffe799e132cf48f8d5 (
plain)
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
|
#include <stdio.h>
#include <stdlib.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* partition(struct ListNode* head, int x) {
struct ListNode *hl = NULL;
struct ListNode *tl = NULL;
struct ListNode *hg = NULL;
struct ListNode *tg = NULL;
struct ListNode *tmp;
if(head == NULL) return head;
for(; head != NULL; head = head->next) {
tmp = malloc(sizeof(struct ListNode));
tmp->val = head->val;
tmp->next = NULL;
if(head->val < x) {
if(tl == NULL)
hl = tl = tmp;
else {
tl->next = tmp;
tl = tl->next;
}
}
else {
if(tg == NULL)
hg = tg = tmp;
else {
tg->next = tmp;
tg = tg->next;
}
}
}
if(hl != NULL) {
tl->next = hg;
} else
return hg;
return hl;
}
|