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.
Example
Given 1->3->8->11->15->null
, 2->null
, return1->2->3->8->11->15->null
.
分析
第一种方法,使用递归,recurring
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class Solution { /** * @param ListNode l1 is the head of the linked list * @param ListNode l2 is the head of the linked list * @return: ListNode head of linked list */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // write your code here if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val){ l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } } } |
第二种方法,使用循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | /** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param ListNode l1 is the head of the linked list * @param ListNode l2 is the head of the linked list * @return: ListNode head of linked list */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // write your code here if (l1 == null) return l2; if (l2 == null) return l1; ListNode dummy = new ListNode(0); ListNode p = dummy; while (l1 != null && l2 != null){ if (l1.val < l2.val){ p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } if (l1 == null) p.next = l2; if (l2 == null) p.next = l1; return dummy.next; } } |