1. 题目描述
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
2. 解题
链表打卡题,没啥好说的,代码如下:
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* res = (struct ListNode *)malloc(sizeof(struct ListNode));
res->next = NULL;
struct ListNode* ptr = res;
while (l1 && l2) {
if (l1->val < l2->val) {
ptr->next = l1;
ptr = ptr->next;
l1 = l1->next;
}
else {
ptr->next = l2;
ptr = ptr->next;
l2 = l2->next;
}
}
ptr->next = l1 ? l1 : l2;
return res->next;
}
主要是想分享一下LeetCode上惊艳的递归解法:
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) return l2;
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;
}
}
这个递归解法比通常解法少了很多指针的操作,最后运行时间甚至比通常解法还快,不禁感慨递归真奇妙!