将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解题思路:
这个题做了快两个小时还是没有做出来,简直怀疑人生!上一次有这种感觉还是高中做数学题的时候!无奈借鉴博友
Leetcode 21:合并两个有序链表(最详细解决方案!!!) - coordinate的博客 - 优快云博客
https://blog.youkuaiyun.com/qq_17550379/article/details/80668769
的思路。
自己的思维困境在于没有想到求助外援呐,压根没想到再创建一个新链表,然后建立两个指针指向两个有序链表,再进行判断!而是一直在原来的链表上折腾,结果给自己绕进去了。另外,博主还提出了使用更简单的递归的思路。
本题得出的教训:
1、要有引入第三方力量解决问题的意识(对本题来说,就是新链表)
2、培养“双指针”解题意识
3、培养使用递归思路解题的意识
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
#我自闭了
#引入外援吧
'''
#双指针解法
head = cur = ListNode(None)
cur1 = l1
cur2 = l2
while cur1 and cur2:
if cur1.val < cur2.val:
cur.next = cur1
cur1 = cur1.next
else:
cur.next = cur2
cur2 = cur2.next
cur = cur.next
if not cur1:
cur.next = cur2
if not cur2:
cur.next = cur1
return head.next
'''
#递归解法
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l2.next, l1)
return l2
C++
方法一:递归
/**
* 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(l2->next, l1);
return l2;
}
}
};
方法二:迭代
/**
* 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;
ListNode* newhead = new ListNode(-1);
ListNode * p1 = newhead;
while(l1 && l2){
if(l1->val < l2->val){
p1->next = l1;
l1 = l1->next;
}
else{
p1->next = l2;
l2 = l2->next;
}
p1 = p1->next;
}
p1->next = (!l1) ? l2 : l1;
return newhead->next;
}
};