标签:
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 3 ListNode p1 = l1; 4 ListNode p2 = l2; 5 6 ListNode fakeHead = new ListNode(0); 7 ListNode p = fakeHead; 8 9 while(p1 != null && p2 != null){ 10 if(p1.val <= p2.val){ 11 p.next = p1; 12 p1 = p1.next; 13 }else{ 14 p.next = p2; 15 p2 = p2.next; 16 } 17 18 p = p.next; 19 } 20 21 if(p1 != null) 22 p.next = p1; 23 if(p2 != null) 24 p.next = p2; 25 26 return fakeHead.next; 27 }
重点是next边界的使用,注意一点 最好使用新指针 不要改动原有的东西。
LeetCode 21 -- Merge Two Sorted Lists
标签:
原文地址:http://www.cnblogs.com/myshuangwaiwai/p/4686605.html