用Python实现合并两个排序的列表,但一直报错,请问怎么修改啊?
classListNode(object):def__init__(self,val):self.val=valself.next=0classSolution(obje...
class ListNode(object):
def __init__(self,val):
self.val = val
self.next = 0
class Solution(object):
def mergeTwoLists(self,l1,l2):
if l1 is None:
return l2
if l2 is None:
return l1
dummyhead=ListNode(0)
dummyhead.next=None
p=dummyhead
while l1 is not None and l2 is not None:
if l1.val<l2.val:
p.next=l1
l1=l1.next
else:
p.next=l2
l2=l2.next
p=p.next
if l1 is not None:
p.next=l1
else:
p.next=l2
return dummyhead.next
l1=[1,3,5,7]
l2=[2,4,6,8]
Solution.mergeTwoLists(l1,l2) 展开
def __init__(self,val):
self.val = val
self.next = 0
class Solution(object):
def mergeTwoLists(self,l1,l2):
if l1 is None:
return l2
if l2 is None:
return l1
dummyhead=ListNode(0)
dummyhead.next=None
p=dummyhead
while l1 is not None and l2 is not None:
if l1.val<l2.val:
p.next=l1
l1=l1.next
else:
p.next=l2
l2=l2.next
p=p.next
if l1 is not None:
p.next=l1
else:
p.next=l2
return dummyhead.next
l1=[1,3,5,7]
l2=[2,4,6,8]
Solution.mergeTwoLists(l1,l2) 展开
2个回答
展开全部
你所定义的list node class和python自带的list type是不同的东西,不能通用,必须先转换
其他小错我直接帮你改掉了
下面是改好可以运行的代码:
class ListNode(object):
def __init__(self,val):
self.val = val
self.next = None
def __repr__(self):
return str(self.val)
def LinkedList(pythonlist):
l = ListNode(pythonlist[0])
c = l
for i in range(1,len(pythonlist)):
l.next = ListNode(pythonlist[i])
l = l.next
return c
def PythonList(ListNode):
l = []
while ListNode != None:
l.append(ListNode.val)
ListNode = ListNode.next
return l
class Solution(object):
def mergeTwoLists(self,l1,l2):
if l1 is None:
return l2
if l2 is None:
return l1
dummyhead=ListNode(0)
dummyhead.next=None
p=dummyhead
while l1 is not None and l2 is not None:
if l1.val<l2.val:
p.next=l1
l1=l1.next
else:
p.next=l2
l2=l2.next
p=p.next
if l1 is not None:
p.next=l1
else:
p.next=l2
return dummyhead.next
l1=LinkedList([1,3,5,7])
l2=LinkedList([2,4,6,8])
sol = Solution()
print(PythonList(sol.mergeTwoLists(l1,l2)))
(LinkedList(pythonlist) 方法把一个传统的python list转换成你用的首位相衔的listnode 形式,PythonList(ListNode) 则是转换回来)
同时,linkedlist的数据类型在c里面比较常用,python里面一般用不着这么麻烦
希望对你有帮助
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询