leetcode21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
def mergeTwoLists(list1, list2):
i = j = 0
c = []
while (i < len(list1) and j < len(list2)):
if list1[i] < list2[j]:
c.append(list1[i])
i += 1
if list1[i] > list2[j]:
c.append(list2[j])
j += 1
else:
c.append(list1[i])
c.append(list2[j])
i += 1
j += 1
return c
res = mergeTwoLists([3,4,2], [4,1,5])
print(res)
Traceback (most recent call last):
File "D:\python_work\20220302.py", line 92, in
res = mergeTwoLists([3,4,2], [4,1,5])
File "D:\python_work\20220302.py", line 82, in mergeTwoLists
if list1[i] > list2[j]:
IndexError: list index out of range
大概看了了一下, 要么,循环条件要改,要么循环体里要做判断
while (i < len(list1)-1 and j < len(list2)-1):
比如 len(list1) = 10
i = 8 时,还可以执行一次循环
i =9 时, 就不能执行了了
因为 list1[9] 是最后一个元素了。