This article is in the study summary, welcome reprint but please specify Source:http://blog.csdn.net/pistolove/article/details/41750865
Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
For example,
Given1->2->3
,4->5->6
,return1->2->3->4->5->6
.
Given1->3->5
,2->4->4,return1->2->3->4->5->6
.
Ideas:
(1) Test instructions to synthesize an ordered list of two ordered linked lists.
(2) First, the list header node is empty, if all is empty, return null, if L1 is empty, L2 is not empty, return L1, if L1 is empty, L2 is not empty, return L2.
(2) Secondly, set the node p as the result chain header node, set the flag nodes Q points to the end of the linked list node.
(3) Again, the loop treats the node traversal in the merged list, if the nodes L1 and L2 are not empty, then compare their node values, if L1<L2, (the first time you need to initialize p and Q values, P=L1,
q=p), will flag The node points to the node L1, the flag node moves back, and L1 points to its subsequent nodes, l1>=l2 similar until the end of the loop.
(4) Finally, it is necessary to determine the nodes that are not compared, append these nodes to the subsequent nodes of Q, and return p as the result.
(5) The comparison process is simple as follows:
Example: L1:1->3->5->13 l2:2->4->14->17
(A) l1=1,l2=2,l1<l2, initial p=l1=1,q=p=1,l1=l1.next=3;
(B) L1=3,l2=2,l1>l2, at this time, q.next=l2=2,q=q.next=2,l2=l2.next=4;
(C) L1=3,l2=4,l1<l2, at this time, q.next=l1=3,q=q.next=3,l1=l1.next=5;
(D) L1=5,l2=4,l1>l2, at this time, q.next=l2=4,q=q.next=4,l2=l2.next=14;
(E) L1=5,l2=14,l1<l2, at this time, q.next=l1=5,q=q.next=5,l1=l1.next=13;
(F) L1=13,l2=14,l1<l2, at this time, q.next=l1=13,q=q.next=13,l1=l1.next=null;
(G) Since L1 is empty, the subsequent nodes in the L2 need to be appended to Q later.
The algorithm code is implemented as follows:
Public ListNode mergetwolists (ListNode L1, ListNode L2) {if (L1 = = NULL && L2 = null return null;if (L1 = Nu ll && L2! = null) return l2;if (L1! = null && L2 = null) return L1; ListNode p = null; ListNode q = p;while (L1! = NULL && L2! = null) {if (L1.val < L2.val) {if (p = = null) {p = l1;q = P; L1 = l1.next;continue;} Q.next = L1;q = Q.next; L1 = L1.next;} else {if (p = = null) {p = l2;q = P; L2 = l2.next;continue;} Q.next = L2;q = Q.next; L2 = L2.next;}} while (L1! = null) {Q.next = L1;q = Q.next; L1 = L1.next;} while (L2! = null) {Q.next = L2;q = Q.next; L2 = L2.next;} return p;}
Merge Sorted Lists