[LintCode] Merge Two Sorted Lists
阿新 • • 發佈:2017-10-13
blog lintcode code sts amp oge pro lint link .
Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
ExampleGiven 1->3->8->11->15->null
, 2->null
, return 1->2->3->8->11->15->null
Key idea:
1. Use a dummy node to simplify head node management;
2. Apply the merge procedure in merge sort.
1 /** 2 * Definition for ListNode. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int val) { 7 * this.val = val; 8 * this.next = null;9 * } 10 * } 11 */ 12 13 14 public class Solution { 15 /* 16 * @param l1: ListNode l1 is the head of the linked list 17 * @param l2: ListNode l2 is the head of the linked list 18 * @return: ListNode head of linked list 19 */ 20 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {21 if(l1 == null) { 22 return l2; 23 } 24 else if(l2 == null) { 25 return l1; 26 } 27 ListNode dummy = new ListNode(0); 28 ListNode curr = dummy, curr1 = l1, curr2 = l2, temp = null; 29 while(curr1 != null && curr2 != null) { 30 if(curr1.val <= curr2.val) { 31 curr.next = curr1; 32 temp = curr1.next; 33 curr1.next = null; 34 curr1 = temp; 35 } 36 else { 37 curr.next = curr2; 38 temp = curr2.next; 39 curr2.next = null; 40 curr2 = temp; 41 } 42 curr = curr.next; 43 } 44 if(curr1 != null) { 45 curr.next = curr1; 46 } 47 else if(curr2 != null) { 48 curr.next = curr2; 49 } 50 return dummy.next; 51 } 52 }
Related Problems
Merge Two Sorted Arrays
[LintCode] Merge Two Sorted Lists