首页 > 代码库 > LeetCode 21. Merge Two Sorted Lists

LeetCode 21. Merge Two Sorted Lists

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.

 

Solution:

1->2->4->5

1->3->4->7->8->10      output should be: 1->1->2->3->4->5->7->8->10

so compare node from l1 and node from l2 to place the value to a new Linked list, stop when either one is end. then paste the rest nodes to the

result list.

 1 public class Solution {
 2     public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
 3         if(l1==null|| l2==null)
 4         {
 5             if(l1==null)
 6             {
 7                 return l2;
 8             }
 9             else
10             {
11                 return l1;
12             }
13         }
14         ListNode n1 = l1; 
15         ListNode n2 = l2;
16         
17         ListNode result = new ListNode(0);
18         if(n1.val<n2.val)
19         {
20             result.val = n1.val;
21             n1 = n1.next;
22         }
23         else
24         {
25             result.val = n2.val;
26             n2 = n2.next;
27         }
28         ListNode r = result;
29         while(n1!=null&&n2!=null)
30         {
31             if(n1.val<n2.val)
32             {
33                 r.next = new ListNode(n1.val);
34                 n1 = n1.next;
35             }
36             else
37             {
38                 r.next = new ListNode(n2.val);
39                 n2 = n2.next ;
40                 
41             }
42             r = r.next;
43         }
44         if (n1!=null)
45         {
46             r.next = n1;
47         }
48         if(n2!=null)
49         {
50             r.next = n2;
51         }
52         return result;
53     }
54 }

 

LeetCode 21. Merge Two Sorted Lists