Merge two sorted lists

Source: Internet
Author: User

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

Ideas: The topic is relatively simple, there are two ideas, one is to traverse the public length of two linked lists, by the size of the value of the various nodes connected, and finally the longer list of the remainder to append to the last. The second idea, which is similar to a natural merge sort, can be solved by using the idea of recursive separation, and it makes it easy for you to break the problem down into sub-problems.

Implementation code

Non-recursive:

/*Public class ListNode {int val;    ListNode next = null;    ListNode (int val) {this.val = val; }}*/ Public classSolution { PublicListNode Merge (listnode list1,listnode list2) {if(List1 = =NULL)            returnList2; if(List2 = =NULL)            returnList1;        ListNode Head; if(list1.val<=list2.val) {head=List1; List1=List1.next; }        Else{Head=List2; List2=List2.next; } ListNode Pnode=Head;  while(List1! =NULL&& List2! =NULL) {            if(List1.val <=list2.val) {Pnode.next=List1; List1=List1.next; }            Else{Pnode.next=List2; List2=List2.next; } Pnode=Pnode.next; }                 while(List1! =NULL) {Pnode.next=List1; Pnode=Pnode.next; List1=List1.next; }                 while(List2! =NULL) {Pnode.next=List2; Pnode=Pnode.next; List2=List2.next; }                returnHead; }}

Recursion:

/*Public class ListNode {int val;     ListNode next = null;    ListNode (int val) {this.val = val; }}*/ Public classSolution { PublicListNode Merge (listnode list1,listnode list2) {if(List1 = =NULL)            returnList2; if(List2 = =NULL)            returnList1;                 ListNode Head; if(List1.val <list2.val) {head=List1; Head.next=Merge (List1.next, List2); }        Else{Head=List2; Head.next=Merge (List1, List2.next); }        returnHead; }}

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.