美文网首页
2018-09-26

2018-09-26

作者: DAFFE | 来源:发表于2018-09-26 11:01 被阅读0次

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


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

相关文章

网友评论

      本文标题:2018-09-26

      本文链接:https://www.haomeiwen.com/subject/hgddoftx.html