Merge Sorted Lists

Source: Internet
Author: User

Merge sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should is made by splicing together the nodes of the and lists in sorted order.

Example

Given 1->3->8->11->15->null , 2->null return 1->2->3->8->11->15->null .

Analysis:

Create a dummy head and add the two list node to the new list.

1 /**2 * Definition for ListNode.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int val) {7 * This.val = val;8 * this.next = null;9  *     }Ten  * } One  */  A  Public classSolution { -     /** - * @param listnode L1 is the head of the linked list the * @param listnode L2 is the head of the linked list - * @return: ListNode head of linked list -      */ -      PublicListNode mergetwolists (listnode L1, ListNode L2) { +         if(L1 = =NULL)return< -         if(L2 = =NULL)returnL1; +          AListNode dummy =NewListNode (integer.min_value); atListNode current =dummy; -          -          while(L1! =NULL&& L2! =NULL) { -             if(L1.val <l2.val) { -Current.next =L1; -L1 =L1.next; in}Else { -Current.next =L2; toL2 =L2.next; +             } -             Current = Current.next; the         } *          $         if(L1! =NULL) {Panax NotoginsengCurrent.next =L1; -}Else { theCurrent.next =L2; +         } A         returnDummy.next; the     } +}

Reprint Please specify source: cnblogs.com/beiyeqingteng/

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.