【发布时间】:2017-06-11 03:24:44
【问题描述】:
编写python程序合并两个排序列表,尝试从键盘输入这两个列表的值,但是在开始运行时尝试输入第一个值,它会出错:
输入list1:1的整数
回溯(最近一次通话最后一次):
文件“C:/Python/PythonProject/mergeTwoLists_leetcode.py”,第 20 行,<module>list1[i] = input("请输入list1的整数:")
IndexError:列表分配索引超出范围
程序是:
class ListNode(object):
def __init__(self,x):
self.val = x
elf.next = None
class MergeTwoLists(object):
def mergeTwoLists(self,l1,l2):
if not li or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = mergeTwoLists(l1,l2.next)
return l2
#input the two integer lists
list1 = []
for i in range(0,6):
list1[i] = input("enter a integer of list1:")
head = ListNode(list1[0])
p = head
for j in list1[1:]:
node = ListNode(j)
p.next = node
p = p.next
l1 = head
list2 = []
for i in range(0,6):
list2[i] = input("enter an integer of list2:")
head = ListNode(list2[0])
p = head
for j in list2[1:]:
node = ListNode(j)
p.next = node
p = p.next
l2 = head
list_result = MergeTwoLists().mergeTwoLists(l1,l2)
print("the list result:")
print(list_result)
你能帮我吗
【问题讨论】:
-
FWIW,除非你有一些复杂的合并逻辑,否则合并列表就像:
[1, 2, 3] + [4, 5, 6],这将产生[1, 2, 3, 4, 5, 6]。
标签: python