-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathNo21.merge-two-sorted-lists.cs
42 lines (39 loc) · 1.01 KB
/
No21.merge-two-sorted-lists.cs
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
37
38
39
40
41
42
/*
* Difficulty:
* Easy
*
* Desc:
* Merge two sorted linked lists and return it as a new list.
* The new list should be made by splicing together the nodes of the first two lists.
*
* Example:
* Input: 1->2->4, 1->3->4
* Output: 1->1->2->3->4->4
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
ListNode res = new ListNode(0);
ListNode head = res;
while (l1 != null || l2 != null) {
int n1 = l1 == null ? int.MaxValue : l1.val;
int n2 = l2 == null ? int.MaxValue : l2.val;
if (n1 >= n2) {
head.next = new ListNode(n2);
l2 = l2.next;
} else {
head.next = new ListNode(n1);
l1 = l1.next;
}
head = head.next;
}
return res.next;
}
}