Skip to content

Commit fbb5aca

Browse files
authored
Create 23-Merge-k-Sorted-Lists.cs
1 parent a35157f commit fbb5aca

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

csharp/23-Merge-k-Sorted-Lists.cs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
}

0 commit comments

Comments
 (0)