1
+ /*
2
+ * Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
3
+ * Created by supercoderx on 2017/8/11.
4
+ */
5
+
6
+ #include "../main.h"
7
+ #include
8
+ #include
9
+
10
+ struct ListNode * mergeKLists (struct ListNode * * lists , int listsSize ) {
11
+ if (listsSize <= 0 ) {
12
+ return NULL ;
13
+ }
14
+ if (listsSize == 1 ) {
15
+ return lists [0 ];
16
+ }
17
+
18
+ struct ListNode * header = lists [0 ], * p , * p1 , * p2 , * node , * prev ;
19
+ int count = 0 , start = 0 ;
20
+
21
+ for (int i = 1 ; i < listsSize ; i ++ ) {
22
+ p1 = header ;
23
+ p2 = lists [i ];
24
+ if (p1 == NULL ) {
25
+ header = p2 ;
26
+ }
27
+ if (p1 == NULL || p2 == NULL ) {
28
+ continue ;
29
+ }
30
+
31
+ count ++ ;
32
+ if (count == 1 ) {
33
+ while (p1 != NULL || p2 != NULL ) {
34
+ node = malloc (sizeof (struct ListNode ));
35
+ node -> next = NULL ;
36
+ if (p1 == NULL ) {
37
+ node -> val = p2 -> val ;
38
+ p2 = p2 -> next ;
39
+ } else if (p2 == NULL ) {
40
+ node -> val = p1 -> val ;
41
+ p1 = p1 -> next ;
42
+ } else {
43
+ if (p1 -> val < p2 -> val ) {
44
+ node -> val = p1 -> val ;
45
+ p1 = p1 -> next ;
46
+ } else {
47
+ node -> val = p2 -> val ;
48
+ p2 = p2 -> next ;
49
+ }
50
+ }
51
+ if (start == 0 ) {
52
+ header = p = node ;
53
+ start = 1 ;
54
+ } else {
55
+ p -> next = node ;
56
+ p = node ;
57
+ }
58
+ }
59
+ } else {
60
+ prev = NULL ;
61
+ while (p1 != NULL || p2 != NULL ) {
62
+ if (p1 == NULL ) {
63
+ node = malloc (sizeof (struct ListNode ));
64
+ node -> next = NULL ;
65
+ node -> val = p2 -> val ;
66
+ if (prev == NULL ) {
67
+ node -> next = header ;
68
+ header = node ;
69
+ } else {
70
+ prev -> next = node ;
71
+ prev = node ;
72
+ }
73
+ p2 = p2 -> next ;
74
+ } else if (p2 == NULL ) {
75
+ break ;
76
+ } else {
77
+ if (p1 -> val < p2 -> val ) {
78
+ prev = p1 ;
79
+ p1 = p1 -> next ;
80
+ } else {
81
+ node = malloc (sizeof (struct ListNode ));
82
+ node -> val = p2 -> val ;
83
+ if (prev == NULL ) {
84
+ node -> next = header ;
85
+ header = node ;
86
+ } else {
87
+ prev -> next = node ;
88
+ node -> next = p1 ;
89
+ }
90
+ prev = node ;
91
+ p2 = p2 -> next ;
92
+ }
93
+ }
94
+ }
95
+ }
96
+
97
+ }
98
+ return header ;
99
+ }
100
+
101
+ void testMergeKLists () {
102
+ int a [] = {-1 , 1 };
103
+ int b [] = {-3 , 1 , 4 };
104
+ int c [] = {-2 ,-1 ,0 ,2 };
105
+ int a1 [] = {1 };
106
+ int a2 [] = {0 };
107
+ struct ListNode * l1 = createList (a , 2 );
108
+ struct ListNode * l2 = createList (b , 3 );
109
+ struct ListNode * l3 = createList (c , 4 );
110
+ struct ListNode * l11 = createList (a1 , 1 );
111
+ struct ListNode * l12 = createList (a2 , 1 );
112
+ struct ListNode * * l = malloc (sizeof (struct ListNode * ) * 4 );
113
+ l [0 ] = l1 ;l [1 ] = l2 ;l [2 ]= l3 ;l [3 ] = l3 ;
114
+ //l[0] = l11;
115
+ //l[1] = l12;
116
+ printList (mergeKLists (l , 3 ));
117
+ }
0 commit comments