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 }

 

转载于:https://www.cnblogs.com/MiaBlog/p/6092150.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值