2
這是我的節點:Python的鏈表大小/刪除功能不工作
class Node(object):
def __init__(self, data, next = None):
self.data = data
self.next_node = next
def get_next(self):
return self.next_node
def set_next(self, next):
self.next_node = next
def get_data(self):
return self.data
def set_data(self):
self.data = data
這是LinkedList的本身:
class LinkedList(object):
def __init__(self, root = None):
self.root = root
self.size = 0
def size(self):
return self.size
def insert(self, data):
new_node = Node (data, self.root)
self.root = new_node
self.size += 1
def delete(self, data):
this_node = self.root
prev_node = None
while this_node:
if this_node.get_data() == data:
if prev_node:
prev_node.set_next(this_node.get_next())
else:
self.root = this_node
self.size -= 1
return True
else:
prev_node = this_node
this_node = this_node.get_next()
return False
def search(self, data):
this_node = self.root
while this_node:
if this_node.get_data() == data:
return data
else:
self.root = this_node.get_next()
return None
def printLL(self):
this_node = self.root
while this_node:
print(this_node.data)
this_node = this_node.get_next()
最後,這些都是我進行測試:
ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.printLL()
ll.delete(2)
ll.printLL()
if ll.search(2):
print("Value 2 found")
else:
print("Value 2 not found")
if ll.search(1):
print("Value 1 found")
else:
print("Value 1 not found")
ll.insert(4)
ll.printLL()
print(str(ll.size()))
我目前得到這個輸出:
2
1
2
1
Value 2 found
Value 1 not found
4
1
Traceback (most recent call last):
File "C:\Users\ErikIngvoldsen\Documents\Python Code\TestCode.py", line 71, in <module>
print(str(ll.size()))
TypeError: 'int' object is not callable
爲什麼對象不可調用?另外,爲什麼我的刪除功能不起作用?作爲參考,這是我的輸出應該是什麼樣子:
2 1
1
Value 2 not found
Value 1 found
4 1
2
還有格式化的問題,但現在我只專注於獲得這種正常工作。
究竟有什麼區別?在調用print(str(ll.size()))時有沒有辦法讓它工作? – Zevvysan
你不能調用一個變量。當你使用「()」時,這意味着你期望執行一個函數。只需要基本的功能Python教程,我認爲你會理解它。 –