0
class _DoublyLinkedBase:
class _Node:
__slots__ ="_element", "_prev", "_next"
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def __init__(self):
self._header = self._Node(None, None, None)
self._trailer = self._Node(None, None, None)
self._header._next = self._trailer
self._trailer._prev = self._header
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self._size == 0
def _insert_between(self, e, predecessor, successor):
newest = self._Node(e, predecessor, successor)
predecessor._next = newest
successor._prev = newest
self._size += 1
return newest
def _delete_node(self, node):
predecessor = node._prev
successor = node._next
predecessor._next = successor
successor._prev = predecessor
self._size -= 1
element = node._element
node._prev = node._next = node._element = None
return element
class LinkedDeque(_DoublyLinkedBase):
def first(self):
if self.is_empty():
raise Empty("Deque is empty")
return self._header._next._element
def last(self):
if self.is_empty():
raise Empty("Deque is empty")
return self._trailer._prev._element
def insert_first(self, e):
self._insert_between(e, self._header, self._header._next)
def insert_last(self, e):
self._insert_between(e, self._trailer._prev, self._trailer)
def delete_first(self):
if self.is_empty():
raise Empty("Deque is empty")
return self._delete_node(self._header._next)
def delete_last(self):
if self.is_empty():
raise Empty("Deque is empty")
return self._delete._node(self._trailer._prev)
的問題是: 當我嘗試這樣做在python:爲什麼我無法在Python中的linkdeque中獲取節點的值?
a = LinkedDeque() ## create a linked deque
b = _DoublyLinkedBase._Node(5, None, None) ## create a node
a.insert_first(b) ##put b in the first place
a.first() ##check the element
Out[42]: <_DoublyLinkedBase._Node instance at 0x117660830>
爲什麼輸出不是5?
上市代碼縮進有問題 –
你爲什麼嵌套類?這使得你的代碼不必要的煩人理解並且沒有任何好處...... –
哦,代碼是從Python中的數據結構和算法一書中複製出來的。 –