Leetcode_linked List_merge, Sorted Lists

Source: Internet
Author: User

21.Merge Sorted Lists

1. Description of the problem:

Merges two ordered linked lists and returns a new ordered list.

2. Solution Ideas:

The problem is very simple. Can be solved by recursion, or by non-recursive solution; Note: If the non-recursive solution is used to find the head node of the new list is uncertain, the dummy node is introduced. Not much to say between the code.

3. Java code:
/** * Definition forsingly-linked list. * Public classListNode {* intVal; * ListNode Next; * ListNode (int x) {Val= x; } * } */ Public classSolution { PublicListNode mergetwolists (listnode L1, ListNode L2) {//Recursive/*listnode ret =NULL;if(L1 = =NULL)returnL2;if(L2 = =NULL)returnL1;if(L1.Val> L2.Val) {ret = L2;        Ret.next = Mergetwolists (L2.NEXT,L1); }Else{ret = L1;        Ret.next = Mergetwolists (L1.NEXT,L2); }returnret;*//* In addition to the dummy node, a lastnode node is introduced to act as the head node for the next merge. Exits when a null pointer is null on a node of L1 or L2 whileLoop and link the head of the non-empty list to the Lastnode->next. */ListNode dummy =NewListNode (0); ListNode lastnode = dummy; while((l1!=NULL) && (l2!=NULL)){if(L2.Val> L1.Val) {lastnode.next = L1;            L1 = L1.next; }Else{lastnode.next = L2;            L2 = L2.next;        } lastnode = Lastnode.next; } Lastnode.next = (l1!=NULL)? L1:l2;returnDummy.next; }}
4. Algorithm Evaluation:

I hope you will correct the communication!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode_linked List_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.