forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sortList.cpp
111 lines (92 loc) · 2.19 KB
/
sortList.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Source : https://oj.leetcode.com/problems/sort-list/
// Author : Hao Chen
// Date : 2014-07-06
/**********************************************************************************
*
* Sort a linked list in O(n log n) time using constant space complexity.
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *mergeTwoLists(ListNode* head1, ListNode* head2);
ListNode *sortList(ListNode *head) {
if (head==NULL || head->next == NULL){
return head;
}
//find the middle place
ListNode *p1=head, *p2=head->next;
ListNode *prev;
while(p2 && p2->next){
prev = p1;
p1 = p1->next;
p2 = p2->next->next;
}
p2 = p1->next;
p1->next = NULL;
return mergeTwoLists(sortList(head), sortList(p2));
}
ListNode *mergeTwoLists(ListNode* head1, ListNode* head2){
ListNode *p1 = head1, *p2=head2;
static ListNode dummy(0);
dummy.next = p1;
ListNode *prev = &dummy;
while(p1 && p2){
if(p1->val < p2->val){
prev = p1;
p1 = p1->next;
}else{
prev->next = p2;
p2 = p2->next;
prev = prev->next;
prev->next = p1;
}
}
if (p2){
prev->next = p2;
}
return dummy.next;
}
void printList(ListNode* h)
{
while(h!=NULL){
printf("%d ", h->val);
h = h->next;
}
printf("\n");
}
ListNode* createList(int a[], int n)
{
ListNode *head=NULL, *p=NULL;
for(int i=0; i<n; i++){
if (head == NULL){
head = p = new ListNode(a[i]);
}else{
p->next = new ListNode(a[i]);
p = p->next;
}
}
return head;
}
int main(int argc, char** argv)
{
int n = 10;
if (argc>1){
n = atoi(argv[1]);
}
srand(time(NULL));
int *a = new int[n];
for(int i=0; i<n; i++){
a[i] = random()%n + 1;
}
ListNode *p = createList(a, n);
printList(p);
printList(sortList(p));
delete[] a;
return 0;
}