我正在创建一个双链接循环列表,但遇到了一些问题。这是我的代码:
#!/usr/bin/env python
class _DoublyLinkedList:
class _Node(object):
__slots__ = '_element', '_prev', '_next'
def __init__(self, element, prev, next):
self._element = element
self._prev = prev
self._next = next
def getNext(self):
return self._next
def __str__(self):
return str(self._element)
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
def first(self): #return but do not remove the element at front
if self.is_empty():
raise Empty("Empty!")
return self._header._next._element
def last(self):
if self.is_empty():
raise Empty("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("Empty!")
return self._delete_node(self._header._next)
def delete_last(self):
if self.is_empty():
raise Empty("Empty!")
return self._delete_node(self._trailer._prev)
def __str__(self):
if self._size == 0:
return '[]'
retString = "["
currentElement = self._header.getNext()
for i in range(self._size):
retString += str(currentElement) +", "
currentElement = self._header.getNext()
return retString[:-2] + ']'
def main():
d = _DoublyLinkedList()
d.insert_first(10)
print(d.__str__())
d.insert_last(23)
d.insert_last(24)
print(d.__str__())
if __name__ == "__main__":
main()
对于初学者来说,正如你所看到的,这根本不是循环的,所以任何指针都会有所帮助,但我想弄清楚的是,为什么我的输出是:
[10]
[10, 10, 10]
这个程序有我试图添加的正确数量的元素,但将它们全部打印为我在前面插入的元素,我不明白为什么。
原因是,每次通过循环,都会得到相同的元素。
currentElement = self._header.getNext()
for i in range(self._size):
retString += str(currentElement) +", "
currentElement = self._header.getNext()
将其更改为:
currentElement = self._header.getNext()
for i in range(self._size):
retString += str(currentElement) +", "
currentElement = currentElement.getNext()