Interview Road (29)-merge two sorted lists (recursive and non-recursive)

Source: Internet
Author: User

List of classes:
class ListNode{        int key;        ListNodenext;    }
Ideas:
    • This and the array are different, do not need to use a double pointer, from the back to come
Code: Recursive
publicmerge(ListNode head1,ListNode head2){        ifnull){            return head2;        }elseifnull){            return head1;        }        null;        if(head1.key < head2.key){            node =head1;            node.next = merge(head1.next,head2);        }else{            node = head2;            node.next = merge(head1,head2.next);        }        return node;    }
Non-recursive
 PublicListNode merge (ListNode Head1,listnode head2) {if(Head1 = =NULL) {return head2; }Else if(Head2 = =NULL) {return head1; } listnode node =NULL;if(Head1.key < Head2.key)            {node = Head1; Head1 = Head1.Next; }Else{node = head2; Head2 = head2.Next; } while(Head1! =NULL&& head2! =NULL){if(Head1.key < Head2.key) {node.Next= Head1; Head1 = Head1.Next; }Else{node.Next= Head2; Head2 = head2.Next; }        }if(Head1 = =NULL) {node = head2; }if(Head2 = =NULL) {node = Head1;    } return node; }

Interview Road (29)-merge two sorted lists (recursive and non-recursive)

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.