[Lintcode] Merge Sorted Lists

Source: Internet
Author: User

Merge Sorted Lists

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 .

Solution:

Linked list in the merge when in fact to have an advantage, it does not need extra space, do not want to array, to open a space to put an array. The operation is also very simple, get a dummy, and then the small directly connected to the line. This is a basic operation and can be used as a function call in other questions.

Code:

/*** Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) {* This.val = val; * This.next = null; *     } * } */  Public classSolution {/**     * @paramListNode L1 is the head of the linked list *@paramListNode L2 is the head of the linked list *@return: ListNode head of linked list*/     PublicListNode mergetwolists (listnode L1, ListNode L2) {if(L1 = =NULL){            returnL2; }        if(L2 = =NULL){            returnL1; } ListNode Dummy=NewListNode (0); ListNode node=dummy;  while(L1! =NULL&& L2! =NULL){            if(L1.val <l2.val) {Node.next=NewListNode (L1.val); L1=L1.next; Node=Node.next; } Else{Node.next=NewListNode (L2.val); L2=L2.next; Node=Node.next; }        }         while(L1! =NULL) {Node.next=NewListNode (L1.val); L1=L1.next; Node=Node.next; }         while(L2! =NULL) {Node.next=NewListNode (L2.val); L2=L2.next; Node=Node.next; }        returnDummy.next; }}
View Code

[Lintcode] 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.