21.Merge Sorted Lists
1. Description of the problem:
Merges two ordered linked lists and returns a new ordered list.
2. Solution Ideas:
The problem is very simple. Can be solved by recursion, or by non-recursive solution; Note: If the non-recursive solution is used to find the head node of the new list is uncertain, the dummy node is introduced. Not much to say between the code.
3. Java code:
/** * Definition forsingly-linked list. * Public classListNode {* intVal; * ListNode Next; * ListNode (int x) {Val= x; } * } */ Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {//Recursive/*listnode ret =NULL;if(L1 = =NULL)returnL2;if(L2 = =NULL)returnL1;if(L1.Val> L2.Val) {ret = L2; Ret.next = Mergetwolists (L2.NEXT,L1); }Else{ret = L1; Ret.next = Mergetwolists (L1.NEXT,L2); }returnret;*//* In addition to the dummy node, a lastnode node is introduced to act as the head node for the next merge. Exits when a null pointer is null on a node of L1 or L2 whileLoop and link the head of the non-empty list to the Lastnode->next. */ListNode dummy =NewListNode (0); ListNode lastnode = dummy; while((l1!=NULL) && (l2!=NULL)){if(L2.Val> L1.Val) {lastnode.next = L1; L1 = L1.next; }Else{lastnode.next = L2; L2 = L2.next; } lastnode = Lastnode.next; } Lastnode.next = (l1!=NULL)? L1:l2;returnDummy.next; }}
4. Algorithm Evaluation:
I hope you will correct the communication!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode_linked List_merge, Sorted Lists