[英]Linked lists with more than one value per node
我正在嘗試在Python 3中的每個節點上實現帶有多個變量(在這種情況下為兩個)的雙鏈表。
首先,我為此創建了一個HashEntry類(在此之后,我將獲得一個哈希表):
class HashEntry(self):
def __init__(self, key, data, p, n):
self.key = int(key)
self.data = str(data)
self.prev = n
self.next = p
然后,我必須將此類用於我的雙重鏈表操作,但是,如果必須創建另一個Node類,或者為每個方法放置兩個值,我不確定該怎么做。試過:
class Node:
def __init__(self, h = HashEntry, p = None, n = None):
# this is where i don't know how to put my hashentry type element
# into the node. i was trying to make it into a single element node.
self.element = h
self.next = n
self.prev = p
class Dlist(self):
def __init__(self):
self.head = None
self.last = None
def insert(self, e):
aux = Node(e, None, None)
if self.head is None:
self.head = self.last
self.head = aux
else:
aux.prev = self.last
aux.next = None
self.last.next = aux
self.last = aux
非常感謝。
除了HashEntry
管理中缺少的部分外,源代碼還顯示了一些錯誤,這些錯誤不允許執行該軟件。
輕微錯誤1 -Python class
不從self
繼承,建議從class object
繼承。
類聲明應為:
class HashEntry(object):
class Dlist(object):
代替:
class HashEntry(self):
class Dlist(self):
輕微錯誤2-在第一個HashEntry
中插入第一個HashEntry
時, self.head
和self.last
之間的混合。
由於self.last
未初始化,因此分配self.head = self.last
無效。
aux = Node(e, None, None)
if self.head is None:
# self.head = self.last <= wrong assignement
self.head = aux
self.last = self.head # assign last based to the head
else:
分析1-使用key
添加HashEntry
管理。
為了創建具有模擬哈希表訪問權限的雙鏈表,第一個鏈表必須管理一種哈希表,第二個鏈表被鏈接到第一個鏈表,以存儲具有相同key
所有節點。
1-在class Dlist
添加一個search(self,key)
函數,以檢查第一個鏈表中aux = Node(e, None, None)
存在節點aux = Node(e, None, None)
的密鑰:
返回的值是
key
的HashEntry
節點,否則為None
。
def search(self,key):
curr = self.head
while (curr is not None):
if (key == curr.element.key):
return (curr)
curr = curr.next
return (None)
2-向class Node
添加一個append(self,nwnode)
函數,以將具有HashEntry.key
的節點nwnode
添加到第二個鏈接列表。
第二個列表必須對node
element
進行標頭。
def append(self,nwnode):
if (self.element.next is None):
self.element.next = nwnode # adding the first homo-key
nwnode.element.prev = self
else:
curr = self.element.next
while (curr.next is not None):
curr = curr.next
curr.next = nwnode # adding others homo-key
nwnode.element.prev = curr
3-將兩個函數連接到class Dlist
的insert(self, e)
中。
當第一個鏈表不為空時,檢查
key
是否存在。
else:
hashnode = self.search(e.key)
然后在第一個鏈表中插入新的HashEntry aux
節點,或將其附加到第二個鏈表中。
if (hashnode is None):
aux.prev = self.last
aux.next = None
self.last.next = aux # insert to the first linked-list
self.last = aux
else:
hashnode.append(aux) # append to the second linked-list
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.