题目来源:链接: [https://leetcode-cn.com/problems/merge-two-sorted-lists/].
21. 合并两个有序链表
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.
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
2.我的解决方案
我的AC代码如下:(遍历两个链表)
/**
* 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* p = l1; //l1头位置
ListNode* q = l2; //l2头位置
ListNode* result = new ListNode(0); //创建返回列表的头结点
ListNode* r = result; //返回链表的尾节点
while(p && q) // q p 同时都不为空 才成立
{
if(q->val > p->val)
{
r->next = p;
r = r->next;
p = p->next;
}
else
{
r->next = q;
r = r->next;
q = q->next;
}
}
if(q)
{
r->next=q;
}
if(p)
{
r->next=p;
}
return result->next;
}
};
官方改进版本(迭代):
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL) return l2;
else if (l2 == NULL) return l1;
else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
作者:abigcat
链接:https://leetcode-cn.com/problems/two-sum/solution/he-bing-liang-ge-you-xu-lian-biao-guan-fang-cban-b/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3.大神们的解决方案
官方递归C++版本
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* prehead = new ListNode(-1);
ListNode* prev = prehead;
while(l1 != NULL && l2 != NULL) {
if(l1->val <= l2->val) {
prev->next = l1;
l1 = l1->next;
} else {
prev->next = l2;
l2 = l2->next;
}
prev = prev->next;
}
prev->next = l1 != NULL ? l1 : l2;
return prehead->next;
}
};
作者:abigcat
链接:https://leetcode-cn.com/problems/two-sum/solution/he-bing-liang-ge-you-xu-lian-biao-guan-fang-cban-b/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
4.我的收获
继续加油啊啊啊 。。。
不能松懈啊啊啊啊~~~!!!
2019/7/17 胡云层 于南京 125