[英]Put node class into linked list class python
這是我第一次學習python,只是想創建一個簡單的鏈表
這是代碼
class node:
def __init__(self, data = None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
def length(self):
cur = self.head
total = 0
while cur.next != None:
total += 1
cur = cur.next
return total
@property
def display(self):
elems = []
cur_node = self.head
while cur_node.next != None:
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
def get(self, index):
if index >= self.length():
print('index out of range')
return None
cur_idx = 0
cur_node= self.head
while True:
cur_node = cur_node.next
if cur_idx == index: return cur_node.data
cur_idx+= 1
def erase(self, index):
if index >= self.length():
print('index out of range')
return None
cur_idx = 0
cur_node = self.head
while True:
last_node = cur_node
cur_node = cur_node.next
if cur_idx == index:
last_node.next = cur_node.next
return
cur_idx+= 1
l1 = linked_list()
l1.append(8)
l1.append(7)
l1.append(6)
l1.append(5)
print(l1.get(0))
print(l1.get(1))
print(l1.get(2))
print(l1.get(3))
一切都很順利,除非我嘗試將節點 class 放入鏈表 class 作為內部 class 如下所示:
class linked_list:
class node:
def __init__(self, data = None):
self.data = data
self.next = None
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
......
(the rest are the same as the code above)
我收到了這個錯誤:
Traceback (most recent call last):
File "c:\blahblah\Basic_exercise.py", line 65, in <module>
l1 = linked_list()
File "c:\blahblah\Basic_exercise.py", line 11, in __init__
self.head = node()
NameError: name 'node' is not defined
1.我在這里錯過了什么邏輯?
2.有什么方法可以將節點 class 視為內部 class 而不會出錯?
您看到的錯誤是由於您引用內部 class 的方式 - 這是一個命名空間問題。 要從其他node
類中消除內部node
class 的歧義,您需要首先使用外部 class 來引用它: linked_list.node
。 例子:
class linked_list:
class node:
def __init__(self, data = None):
self.data = data
self.next = None
def __init__(self):
self.head = linked_list.node()
def append(self, data):
new_node = linked_list.node(data)
cur = self.head
while cur.next != None:
cur = cur.next
cur.next = new_node
如果要將節點 class 保留在鏈接列表 class 中,則需要從鏈接列表 ZA2F2ED4F8EBC2B61DZC 中調用節點 class。 所以要做到這一點,你必須做new_node = linked_list.node(data)
。 Rest 都應該一樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.