概念
双向链表(Double_linked_list)也叫双链表,是链表的一种,它的每个数据结点中都有
两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可
以很方便地访问它的前驱结点和后继结点。
实现
class Node:
def __init__(self, data):
self.data = data # 数据域
self.next = None # 指针域(直接后继)
self.prev = None # 指针域(直接前驱)
class DoubleLinkedList:
"""
双向链表
"""
def __init__(self):
self._head = None
# 判断链表是否为空
def is_empty(self):
return bool(self._head)
# 返回链表长度
@property
def size(self):
current = self._head
count = 0
while current is not None:
count += 1
current = current.next
return current
# 遍历链表
def travel(self):
current = self._head
while current is not None:
print(current.data)
current = current.next
# 在链表头部插入元素
def add(self, value):
new_node = Node(value)
if self.is_empty():
self._head = new_node
else:
new_node.next, self._head.prev = self._head, new_node
self._head = new_node
# 在链表尾部插入元素
def append(self, value):
new_node = Node(value)
if self.is_empty():
self._head = new_node
else:
_current = self._head
while _current.next is not None:
_current = _current.next
_current.next, new_node.prev = new_node, _current
# 查找元素是否存在
def search(self, value):
_current = self._head
while _current is not None:
if _current.data == value:
return True
_current = _current.next
return False
# 在指定位置插入节点
def insert(self, position, value):
if position < 0 or position > self.size:
raise IndexError("Position out of range.")
if position == 0:
self.add(value)
else:
_node = Node(value)
_current = self._head
i = 0
while i != position:
i += 1
_current = _current.next
_prev = _current.prev
_prev.next, _node.prev = _node, _prev
_node.next, _current.prev = _current, _node
# 删除指定位置的节点
def remove(self, position):
if self.is_empty():
return None
if position < 0 or position > self.size - 1:
raise IndexError("Position out of range.")
_current = self._head
i = 0
while i != position:
i += 1
_current = _current.next
_prev = _current.prev
_next = _current.next
_prev.next, _next.prev = _next, _prev
_current.next, _current.prev = None, None