forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21-Merge-Two-Sorted-Lists.cs
More file actions
36 lines (33 loc) · 918 Bytes
/
21-Merge-Two-Sorted-Lists.cs
File metadata and controls
36 lines (33 loc) · 918 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode MergeTwoLists(ListNode list1, ListNode list2) {
var dummy = new ListNode();
var tail = dummy;
while(list1 is not null && list2 is not null) {
if(list1.val < list2.val) {
tail.next = list1;
list1 = list1.next;
}
else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}
if(list1 is not null)
tail.next = list1;
else if(list2 is not null)
tail.next = list2;
return dummy.next;
}
}