1. Question
Merging two ordered linked lists, the new linked list is returned by stitching the original two linked list to get
return New new list should is made by splicing together the nodes of the first of the lists.
2. Solution (O (m+n))
Consider the following special cases:
- The list is empty: Empty, one is empty
- Two-linked lists are sorted in different ways
To facilitate processing, new an empty node is used as the head of the resulting list, which points to L1, and then merges the L2 into the linked list
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {* val = x; * next = NULL; *} *}*/ Public classSolution {//true is non-descending, false is descending Public BooleanCompareintAintb) { if(A>B)return false; return true; } PublicListNode reverselist (listnode l) {if(l==NULL|| l.next==NULL)returnl; ListNode P=l; ListNode Q=L.next; L.next=NULL; Do{ListNode Next=Q.next; Q.next=p; P=Q; Q=Next; } while(q!=NULL); returnp; } PublicListNode mergetwolists (listnode L1, ListNode L2) {if(l1==NULL)returnL2; if(l2==NULL)returnL1; //if the order of the lists is different, reverse List L2 if(l1.next!=NULL&& l2.next!=NULL&& Compare (L1.val, l1.next.val)! =Compare (L2.val,l2.next.val)) L2=Reverselist (L2); //if the order of the lists is same Booleanorder; if(l1.next!=NULL) Order =Compare (L1.val,l1.next.val); Else if(L2.next! =NULL) Order =Compare (L2.val, l2.next.val); ElseOrder =true; //P is the present end pointer of the result list, L2 is the present inserting pointer of the list L2.ListNode p =NewListNode (0); P.next=L1; ListNode Res=p; Do{ if(Compare (p.next.val,l2.val) = =order) P=P.next; Else{ListNode Q=L2; for(; q.next!=NULL&& Compare (P.next.val, q.next.val)!=order; q=q.next); ListNode Temp=P.next; P.next=L2; L2=Q.next; Q.next=temp; P=temp; } } while(p.next!=NULL&& l2!=NULL ); if(l2!=NULL) P.next=L2; returnRes.next; }}
View Code
Merge sorted lists