https://leetcode-cn.com/explore/interview/card/bytedance/244/linked-list-and-tree/1048/
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
一个个比较吧,遇到小的就放在新的链表中,在更新的时候注意几个问题:
- 记得保存新链表的头部用于返回!
- 遍历往后,l1或者l2会有剩余的,记得要遍历完整
代码如下:
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 and not l2:
return None
if not l1:
return l2
if not l2:
return l1
new_list = None
new_list_head = None
while l1 and l2:
tmp = l1
if l1.val > l2.val:
tmp = l2
if new_list:
new_list.next = tmp
new_list = new_list.next
else:
new_list = tmp
new_list_head = tmp
if l1.val>l2.val:
l2 = l2.next
else:
l1 = l1.next
if l1:
while l1:
new_list.next = l1
new_list = new_list.next
l1 = l1.next
if l2:
while l2:
new_list.next = l2
new_list = new_list.next
l2 = l2.next
return new_list_head