Merge two sorted lists

Source: Internet
Author: User

Input two monotonically increasing list, output two list of linked lists, of course, we need to synthesize the linked list to meet the monotone non-reduction rules.

Idea: There can be two methods of implementation, the first is through the recursive implementation, the second is through non-recursive implementation.

 Public classSolution { PublicListNode Merge (listnode list1,listnode list2) {if(List1 = =NULL&& List2 = =NULL){            return NULL; }        if(List1 = =NULL&& list2!=NULL){            returnList2; }        if(list1!=NULL&&list2==NULL){            returnList1; } listnode Merge=NULL; if(List1.val <list2.val) {Merge=List1; Merge.next=Merge (LIST1.NEXT,LIST2); }Else{Merge=List2; Merge.next=Merge (List1,list2.next); }        returnmerge; }}

Non-recursive:

Public ListNode Merge (ListNode list1,listnode list2) {if (List1 = = NULL && List2 = = null) {retur        n null;        } if (List1 = = null && list2!=null) {return list2;        } if (List1!=null&&list2==null) {return list1;        } ListNode merge = null;        ListNode merge2 = null;                    while (List1!=null &&list2!=null) {if (list1.val<list2.val) {if (merge = = null) { Merge2 = merge = List1; //Make sure the head node}else{merge.next = List1;                Merge = Merge.next;            } list1 = List1.next;                }else{if (merge = = null) {merge2 = merge = List2;                    }else{merge.next = List2; Merge = Merge.next;            This also wants to shift} LIST2 = List2.next; }} if (list1!=null) {merge.next = List1;//node assignment can} if (List2!=null) {Mer        Ge.next = List2;    } return merge2; }

  

Merge two 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.