一种更复杂的链表是双向链表或双面链表。每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;另一个指向下一个节点,当此节点为最后一个节点时,指向空值。
class Node(object):
"""节点"""
def __init__(self, item):
self.elem = item
self.next = None
self.prev = None
class DoubleLink(object):
"""双链表"""
def __init__(self, node=None):
self.__head = node
def is_empty(self):
"""链表是否为空"""
return self.__head is None
def length(self):
"""链表长度"""
cur = self.__head
# count记录数量
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
cur = self.__head
while cur is not None:
print(cur.elem, end=" ") # end