Merge Sorted Lists Leetcode

Source: Internet
Author: User

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.

The title means merging two linked lists and not using extra space (the new chain is made up of two links)

Ideas:

Simple, direct definition of two pointers, pointing to two chains, and comparing the size of the pointing node if the pointer points to a small value, then let the new chain point to the small one, and the pointer moves backwards

, the current pointer of the new chain also moves backwards. Until one of the two chains is traversed to the end, then the remaining chains are stitched to the new chain

The code is as follows:

<span style= "FONT-SIZE:18PX;" >/** * Definition for singly-linked list. * struct ListNode {*     int val; *     ListNode *next; *     listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public:    listnode *mergetwolists (ListNode *l1, ListNode *l2) {            if (l1==null)        return L2;    if (l2==null)        return L1;        ListNode *p,*q;    P=L1;    Q=L2;        ListNode *result=new listnode (0);    ListNode *temp =result;    while (p&&q)    {        if (p->val<q->val)        {            temp->next=p;            temp=p;            p=p->next;                    }        else        {            temp->next=q;            temp=q;            q=q->next;        }    }        if (p)    {        temp->next=p;    }    if (q)    {        temp->next=q;    }        Return result->next;    }}; </span>


Merge Sorted Lists leetcode

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.