题目描述:
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
思路:
将两个排好序的链表合并,依次比较两个链表的数字,存入第三个链表中
1 public class Solution21 { 2 public ListNode mergeTwoLists(ListNode l1,ListNode l2){ 3 ListNode l3 = new ListNode(0); 4 ListNode dummy = l3; 5 while(l1 != null && l2 != null){ 6 if(l1.val< l2.val){ 7 l3.next =l1; 8 l1 = l1.next; 9 }else { 10 l3.next = l2; 11 l2 = l2.next; 12 } 13 l3 = l3.next; 14 } 15 l3.next = (l1 == null)?l2:l1; 16 return dummy.next; 17 } 18 public static void main(String[] args){ 19 // TODO Auto-generated method stub 20 Solution21 solution21 = new Solution21(); 21 ListNode l1 = new ListNode(1); 22 ListNode l2 = new ListNode(2); 23 24 System.out.println(solution21.mergeTwoLists(l1, l2)); 25 } 26 27 }