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
解答:
1 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 2 ListNode dummyHead = new ListNode(0); 3 ListNode p = dummyHead; 4 5 while(l1 != null && l2 != null) { 6 if(l1.val < l2.val) { 7 p.next = l1; 8 l1 = l1.next; 9 } else { 10 p.next = l2; 11 l2 = l2.next; 12 } 13 14 p = p.next; 15 } 16 17 if(l1 != null) { 18 p.next = l1; 19 } 20 21 if(l2 != null) { 22 p.next = l2; 23 } 24 25 return dummyHead.next 26 }
积沙成塔