class Node:
"""链表节点"""
def __init__(self, val, prev=None, next_=None):
self.val = val
self.prev = prev
self.next_ = next_
def __repr__(self):
return str(self.val)
class DoubleLinkedList:
"""双向链表"""
def __init__(self):
self.head = Node("head")
self.tail = Node("tail")
self.head.next_ = self.tail
self.tail.prev = self.head
self.size = 0
def append(self, node):
tail_node = self.tail.prev
node.prev = tail_node
node.next_ = tail_node.next_
tail_node.next_ = node
node.next_.prev = node
self.size += 1
def delete(self, node):
prev = node.prev
next_ = node.next_
prev.next_ = next_
next_.prev = prev
self.size -= 1
if __name__ == '__main__':
# 创建双向链表
double_linked_list = DoubleLinkedList()
# 增加三个元素
double_linked_list.append(Node(110))
double_linked_list.append(Node(120))
double_linked_list.append(Node(119))
# 删除一个元素
double_linked_list.delete(double_linked_list.tail.prev.prev)
# 从头部获取元素或从尾部获取元素
print(double_linked_list.head.next_.next_)
print(double_linked_list.tail.prev.prev)