Merge sorted lists

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.