Skip to content

Commit aebc511

Browse files
authored
merge-two-sorted-lists.cs
1 parent 05556e4 commit aebc511

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

C#/merge-two-sorted-lists.cs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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+
public class Solution
13+
{
14+
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
15+
{
16+
ListNode curr = new ListNode(0);
17+
ListNode dummy = curr;
18+
19+
while (l1 != null && l2 != null)
20+
{
21+
if (l1.val < l2.val)
22+
{
23+
curr.next = l1;
24+
l1 = l1.next;
25+
}
26+
else
27+
{
28+
curr.next = l2;
29+
l2 = l2.next;
30+
}
31+
curr = curr.next;
32+
}
33+
34+
curr.next = l1 ?? l2;
35+
36+
return dummy.next;
37+
}
38+
}
39+
40+
/** SOLUTION TWO **/
41+
42+
public class Solution {
43+
public ListNode MergeTwoLists(ListNode list1, ListNode list2) {
44+
ListNode dummy = new ListNode(-1);
45+
ListNode current = dummy;
46+
47+
while (list1 != null && list2 != null) {
48+
if (list1.val < list2.val) {
49+
current.next = list1;
50+
list1 = list1.next;
51+
} else {
52+
current.next = list2;
53+
list2 = list2.next;
54+
}
55+
current = current.next;
56+
}
57+
58+
if (list1 != null) {
59+
current.next = list1;
60+
}
61+
62+
if (list2 != null) {
63+
current.next = list2;
64+
}
65+
66+
return dummy.next;
67+
}
68+
}

0 commit comments

Comments
 (0)