2018-09-26

2018-09-26  本文已影响0人  DAFFE

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。


ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

        if(!l2)return l1;

        if(!l1)return l2;

        ListNode*phead=new ListNode(0);

        ListNode*ptail=phead;

        while(l1&&l2){

            if(l1->val<=l2->val){ptail->next=l1;l1=l1->next;}

            else{ptail->next=l2;l2=l2->next;}

            ptail=ptail->next;

        }

        if(!l1){ptail->next=l2;}

        if(!l2){ptail->next=l1;}

        return phead->next;

    }

image
上一篇 下一篇

猜你喜欢

热点阅读