[英]Intersection of two sorted Linked lists in python3?
我的代碼無法兩次打印出新的列表,該列表是兩個排序的鏈表的交集。它無法訪問函數內部的列表。 請指出我的代碼中的錯誤。 我的代碼中沒有縮進問題,該算法似乎也不錯。
class Node(object):
def __init__(self,data):
self.data = data
self.next = None
class Linked(object):
def __init__(self):
self.head = None
def push(self,n):
new_node = Node(n)
new_node.next = self.head
self.head = new_node
def print_list(self):
current = self.head
while current:
print(current.data)
current = current.next
def intersect(self,l1,l2):
l1 = l1.head
l2 = l2.head
dummy = cur = Node(0)
while l1 and l2:
if l2.data>l1.data:
l1=l1.next
elif l1.data>l2.data:
l2=l2.next
else:
cur.next = l1 or l2
l1 = l1.next
l2 = l2.next
cur = cur.next
return dummy.next
llist = Linked()
llist1 = Linked()
llist.push(6)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
llist1.push(8)
llist1.push(6)
llist1.push(4)
llist1.push(2)
l = Linked()
print(l.intersect(llist,llist1).data)
這是回溯:
Traceback (most recent call last):
File "C:/Users/omsai/Desktop/intersection.py", line 48, in <module>
print(l.intersect(llist,llist1).data)
File "C:/Users/omsai/Desktop/intersection.py", line 26, in intersect
if l2.data>l1.data:
AttributeError: 'Linked' object has no attribute 'data'
您正在用兩個Linked
實例調用Linked.intersect
,后者沒有data
成員。 您需要使用intersect
方法獲取實際節點:
def intersect(self,l1,l2):
l1 = l1.head
l2 = l2.head
dummy = cur = Node(0)
# ...
您可能不需要用兩個參數調用intersect
; 將一個列表與另一個列表相交就足夠了:
def intersect(self, olinked):
thisone = self.head
otherone = olinked.head
retval = Linked()
while thisone and otherone:
if otherone.data > thisone.data:
thisone = thisone.next
elif thisone.data > otherone.data:
otherone = otherone.next
else: # thisone.data == otherone.data
retval.push(otherone.data)
thisone = thisone.next
otherone = otherone.next
return retval
# ...
llist.intersect(llist1).print_list()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.