【leetcode】14. 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) {
        if(!l1)
            return l2;
        if(!l2)
            return l1;
        if(l1->val <= l2->val){
            l1->next = mergeTwoLists(l1->next,l2);
            return l1;
        }
        else{
            l2->next = mergeTwoLists(l1,l2->next);
            return l2;
        }
        
    }
};

用的是一个递归的方法,实际上效率很低,仅打败33%,对于

 ListNode(int x) : val(x), next(NULL) {}

相当于一个构造函数,val 初值为x,next 为null.

相关文章: