Skip to content

Commit 45fcf00

Browse files
committed
Create 21-Merge-Two-Sorted-Lists.cs
1 parent bd40ef5 commit 45fcf00

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
public ListNode MergeTwoLists(ListNode list1, ListNode list2) {
14+
var dummy = new ListNode();
15+
var tail = dummy;
16+
17+
while(list1 is not null && list2 is not null) {
18+
if(list1.val < list2.val) {
19+
tail.next = list1;
20+
list1 = list1.next;
21+
}
22+
else {
23+
tail.next = list2;
24+
list2 = list2.next;
25+
}
26+
tail = tail.next;
27+
}
28+
29+
if(list1 is not null)
30+
tail.next = list1;
31+
else if(list2 is not null)
32+
tail.next = list2;
33+
34+
return dummy.next;
35+
}
36+
}

0 commit comments

Comments
 (0)