LeetCode 20-5 每日一题

上个月没搞完,看这个月能不能坚持下来咯

Day1: 合并有序链表,经典题,写一个空节点当头。

/**
 * 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* ret = new ListNode(0,NULL);
        ListNode* cur = ret;
        while(l1 && l2){
            if(l1->val < l2->val){
                cur->next = l1;
                l1 = l1->next;
            }else{
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        if(l1){
            cur->next = l1;
        }
        if(l2){
            cur->next = l2;
        }
        return ret->next;
    }
};

猜你喜欢

转载自www.cnblogs.com/xxrlz/p/12813648.html