首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。