Merge sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should is made by splicing together the nodes of the and lists in sorted order.
Example
Given 1->3->8->11->15->null
, 2->null
return 1->2->3->8->11->15->null
.
Analysis:
Create a dummy head and add the two list node to the new list.
1 /**2 * Definition for ListNode.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int val) {7 * This.val = val;8 * this.next = null;9 * }Ten * } One */ A Public classSolution { - /** - * @param listnode L1 is the head of the linked list the * @param listnode L2 is the head of the linked list - * @return: ListNode head of linked list - */ - PublicListNode mergetwolists (listnode L1, ListNode L2) { + if(L1 = =NULL)return< - if(L2 = =NULL)returnL1; + AListNode dummy =NewListNode (integer.min_value); atListNode current =dummy; - - while(L1! =NULL&& L2! =NULL) { - if(L1.val <l2.val) { -Current.next =L1; -L1 =L1.next; in}Else { -Current.next =L2; toL2 =L2.next; + } - Current = Current.next; the } * $ if(L1! =NULL) {Panax NotoginsengCurrent.next =L1; -}Else { theCurrent.next =L2; + } A returnDummy.next; the } +}
Reprint Please specify source: cnblogs.com/beiyeqingteng/
Merge Sorted Lists