LeetCode21: 合并两个有序链表
合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
示例3:
输入:l1 = [], l2 = [0] 输出:[0]
解题思路
我们依次比较l1和l2的最开始的数值的大小,把小的那个放入到curr.next中。最后面可能会有剩余的l1或者l2非空,那就把剩余的,拼接在curr的后面。
注意,我们用dump指向curr,curr.next就是我们需要返回的内容。即返回dump.next即可。
Java代码
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode curr = new ListNode(0);
ListNode dump = curr;
while (list1 != null && list2 != null){
if (list1.val < list2.val){
curr.next = list1;
list1 = list1.next;
}else {
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
}
if (list1 != null){
curr.next = list1;
}
if (list2 != null){
curr.next = list2;
}
return dump.next;
}
}
Python代码
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
curr = dumy = ListNode(0)
while list1 and list2:
if list1.val < list2.val:
curr.next = list1
list1 = list1.next
else:
curr.next = list2
list2 = list2.next
curr = curr.next
curr.next = list1 or list2
return dumy.next