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 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 ListNode root = new ListNode(-1); 17 ListNode cur1 = l1; 18 ListNode cur2 = l2; 19 ListNode cur3 = root; 20 while(cur1 != null && cur2 != null){ 21 if(cur1.val < cur2.val){ 22 cur3.next = cur1; 23 cur3 = cur1; 24 cur1 = cur1.next; 25 }else{ 26 cur3.next = cur2; 27 cur3 = cur2; 28 cur2 = cur2.next; 29 } 30 } 31 if(cur1 == null){ 32 cur3.next = cur2; 33 } 34 if(cur2 == null){ 35 cur3.next = cur1; 36 } 37 return root.next; 38 } 39 }
第三遍:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 14 ListNode header = new ListNode(-1); 15 ListNode cur = header, cur1 = l1, cur2 = l2; 16 while(cur1 != null || cur2 != null){ 17 int aa = cur1 != null ? cur1.val : Integer.MAX_VALUE; 18 int bb = cur2 != null ? cur2.val : Integer.MAX_VALUE; 19 if(aa > bb){ 20 cur.next = cur2; 21 cur2 = cur2.next; 22 cur = cur.next; 23 } else { 24 cur.next = cur1; 25 cur1 = cur1.next; 26 cur = cur.next; 27 } 28 } 29 return header.next; 30 } 31 }
posted on 2013-10-02 14:40 Step-BY-Step 阅读(160) 评论(0) 编辑 收藏 举报