Lintcode 165 Merge two sorted list __ List

Source: Internet
Author: User
Tags lintcode

1. Problem Description: Merge two sorted list into a new sort list

2. Solving ideas: Traversing the public length of two linked lists, depending on the size of the node to change the connection of each node, and then judge that the list has surplus, and finally the remaining parts of the long list appended to the back of the node

3. Code adopted:

/**
* Definition of ListNode
* Class ListNode {
* Public:
* int val;
* ListNode *next;
* ListNode (int val) {
* This->val = val;
* This->next = NULL;
*     }
* }
*/
Class Solution {
Public
/**
* @param listnode L1 is the head of the linked list
* @param ListNode L2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergetwolists (ListNode *l1, ListNode *l2)
{
Write your code here
ListNode *dummy=new listnode (0);
ListNode *temp=dummy;
while (L1&&L2)
{
if (l1->val<=l2->val) {temp->next=l1;l1=l1->next;temp=temp->next;}
Else{temp->next=l2;l2=l2->next;temp=temp->next;}
}
if (l1!=null) {temp->next=l1;}
else {temp->next=l2;}
Return dummy->next;
}
};

4. Impressions:

This problem is the insertion of a sort of expansion problem, he has given two of the list has been sorted, so if they understand the idea, it will be very easy to come out, the difficulty is divided into the circumstances of the time to consider and deal with.

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.