lintcode-Merge two sorted list __ List

Source: Internet
Author: User
Tags lintcode

Topic Description: Merge two sorted lists into a new sort list

examples

Give the 1->3->8->11->15->null,2->null and return to 1->2->3->8->11->15->null.

The idea: Use two head nodes L1 and L2 traverse two linked list, compare the size of the node value, the small one into the new linked list, the new linked list to define a head node, point to the node put into the value, move to the next node, to consider the beginning of the first linked list is empty, and traversal of a linked list in advance to the empty situation.

Key code: ListNode *mergetwolists (ListNode *l1,listnode *l2) {

Write your code here

ListNode *head=null;

ListNode *p=head;

ListNode *p1=l1;

ListNode *p2=l2;

if (l1==null) return L2;

if (l2==null) {return L1;}

while (P1!=null&&p2!=null)

{if (p1->val<p2->val)

{p->next=p1;

p1=l1->next;

}

else {p->next=p2;

P2=l2->next;}

p=p->next;

}

if (p1==null) p->next=p2;

if (p2==null) {p->next=p1;}

return head;

   } Feelings: This problem I stay up all the time to change, has been submitted is out of bounds, do not know where is wrong, very anxious, and then the code to the students to see, I found that I have just begun to define the new linked list of the first node is empty is not correct, because the head node in the data field has a value, However, it is not used, and the header node cannot be returned when returned, because NULL is defined. It was later changed to the assignment of a node, which is returned when the head node points to the starting node. was successful.

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.