Leetcode-21-merge Sorted Lists

Source: Internet
Author: User

Title: Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
Merges two ordered linked lists sequentially.
Mainly the operation of the list, linked to the list of questions to take C + + to do.

Idea: Compare the Val value of the current element of the two linked list in turn, p points to the small one, and the small pointer moves back. Note that if the list is empty, the pointer moves back to a null-out loop, and if the following determines which is not empty then P points to its string.

C++:

/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */ class solution {public:listnode* mergetwolists (listnode* L1, listnode* L2) {listnode* p=NewListNode (0); listnode* q=p;//q Save Linked list header         while(L1 && L2) {if(l1->Val>= l2->Val) {p->next=l2;            l2=l2->next; }Else{p->next=l1;            l1=l1->next; } p=p->next;//Note that the P pointer also moves back}if(L1) p->next=l1;if(L2) p->next=l2;returnq->next;//Start from the second node, discard the beginning of the 0}};

10ms AC.

Put on a python:

 class solution(object):    "' Test instructions: Merging two ordered linked lists '     def mergetwolists(self, L1, L2):dummy = ListNode (0) TMP = Dummy whileL1! =None  andL2! =None:ifL1.val < L2.val:tmp.next = L1 L1 = L1.nextElse: Tmp.next = L2 L2 = l2.next tmp = Tmp.nextifL1! =None: Tmp.next = L1Else: Tmp.next = L2returnDummy.next

Similar.

Leetcode-21-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.