21. Merge Two Sorted Lists的C++解法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/85233332

题目描述:https://leetcode.com/problems/merge-two-sorted-lists/

注意构造方式以及新建一个列表头的处理方法。

class Solution {
public:
    ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) {
        ListNode *res=new ListNode(0);
        ListNode *ans=res;
        while (l1!=NULL && l2!=NULL)
        {
            if (l1->val<l2->val)
            {res->next=l1;l1=l1->next;}
            else {res->next=l2;l2=l2->next;}
            res=res->next;
        }
        if (l1!=NULL) res->next=l1;
        if (l2!=NULL) res->next=l2;
        return ans->next;
    }
};

猜你喜欢

转载自blog.csdn.net/musechipin/article/details/85233332