当前位置:编程学习 > C/C++ >>

Merge two sorted linked lists

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.


代码如下:

       struct ListNode {
            int val;
            ListNode *next;
            ListNode(int x) : val(x), next(NULL) {}
       };

        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1==NULL)return l2;
        if(l2==NULL)return l1;
        ListNode *head1=NULL,*head2=NULL;
        if(l1->val<=l2->val)
        {
            head1=l1;
            head2=l2;
        }
        else
        {
            head1=l2;
            head2=l1;
        }
        ListNode *head=head1;
        while(head2!=NULL)
        {
            while(head1->next!=NULL&&head1->next->val<=head2->val)
            {
               head1=head1->next;
            }
            if(head1->next==NULL)
            {
                head1->next=head2;
                break;
            }
            else
            {
               ListNode *tmp=head2;
               head2=head2->next;
               tmp->next=head1->next;
               head1->next=tmp;
               head1=tmp;
            }
        }
        return head;
    }


 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,