The Dream Of leozp

try my best

Leetcode: Merge Two Sorted Lists
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *ans=new ListNode(0);
        ListNode *answer=ans;
        while(l1 && l2){
            if(l1->val<l2->val){
                ans->next=l1;
                ans=ans->next;
                l1=l1->next;
            }
            else{
                ans->next=l2;
                l2=l2->next;
                ans=ans->next;
            }
        }
        if(l1){
            ans->next=l1;
        }
        if(l2){
            ans->next=l2;
        }
        
        return answer->next;
    }
};

阅读更多
版权声明:本文为博主原创文章,欢迎指教~ https://blog.csdn.net/u013712847/article/details/52386584
文章标签: leetcode 合并
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Leetcode: Merge Two Sorted Lists

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭