问题遇到的现象和发生背景
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