21. Merge Two Sorted Lists
problem description
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
algorithm thought
之前也提到了,碰到链表题并且返回值是链表的情况下,可以首先考虑能否用递归解题。这题正好可以。和之前链表加法很相似,可能还简单一点
code
/**
* 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==NULL)
return l2;
else if(l2==NULL)
return l1;
if(l1->val<l2->val){
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}else{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
return NULL;
}
};
algorithm analysis
时间复杂度O(n)的,递归肯定是比迭代方法慢一点的,但是两种方法时间复杂度是一样的。之后有时间来实现以下迭代版本的把。
Last updated