File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * public class ListNode {
4
+ * public int val;
5
+ * public ListNode next;
6
+ * public ListNode(int val=0, ListNode next=null) {
7
+ * this.val = val;
8
+ * this.next = next;
9
+ * }
10
+ * }
11
+ */
12
+
13
+ public class Solution {
14
+ public ListNode MergeKLists ( ListNode [ ] lists ) {
15
+ if ( lists . Length == 0 )
16
+ {
17
+ return null ;
18
+ }
19
+
20
+ while ( lists . Length > 1 )
21
+ {
22
+ var mergedLists = new ListNode [ ( lists . Length + 1 ) / 2 ] ;
23
+ for ( int i = 0 ; i < lists . Length ; i += 2 )
24
+ {
25
+ var l1 = lists [ i ] ;
26
+ var l2 = ( i + 1 < lists . Length ) ? lists [ i + 1 ] : null ;
27
+ mergedLists [ i / 2 ] = ( MergeLists ( l1 , l2 ) ) ;
28
+ }
29
+ lists = mergedLists ;
30
+ }
31
+
32
+ return lists [ 0 ] ;
33
+ }
34
+
35
+ public ListNode MergeLists ( ListNode l1 , ListNode l2 )
36
+ {
37
+ var sorted = new ListNode ( ) ;
38
+ var current = sorted ;
39
+
40
+ while ( l1 != null && l2 != null )
41
+ {
42
+ if ( l1 . val <= l2 . val )
43
+ {
44
+ current . next = l1 ;
45
+ l1 = l1 . next ;
46
+ }
47
+ else
48
+ {
49
+ current . next = l2 ;
50
+ l2 = l2 . next ;
51
+ }
52
+ current = current . next ;
53
+ }
54
+
55
+ if ( l1 != null )
56
+ {
57
+ current . next = l1 ;
58
+ } else
59
+ {
60
+ current . next = l2 ;
61
+ }
62
+
63
+ return sorted . next ;
64
+ }
65
+ }
You can’t perform that action at this time.
0 commit comments