双向链表:
- 即每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。当节点既是头结点又是尾节点时,两个链接均为空值。
# 双向链表基于Python语言的实现
'''
双向链表需要实现的方法:
is_empty() 链表是否为空
len() 链表长度
travel() 遍历整个链表
add(item) 链表头部添加元素
append(item) 链表尾部添加元素
insert(pos, item) 指定位置添加元素
remove(item) 删除节点
search(item) 查找节点是否存在
'''
class Node(object):
"""
节点类
"""
def __init__(self, value):
# 元素域
self.value = value
# 指向下节点 尾节点时为空
self.next = None
# 指向前节点 头节点时为空
self.prev = None
class BothWayLinkList(object):
"""
双向链表类
"""
def __init__(self, node=None):
# 初始化头节点
self.__head = node
def __len__(self):
"""
返回链表长度
"""
# 游标,用来遍历链表
cur = self.__head
# 记录遍历次数
count = 0
# 当前节点为None则说明已经遍历完毕
while cur:
count += 1
cur = cur.next
return count
def is_empty(self):
"""
判断链表是否为空
"""
# 头节点不为None则不为空
return self.__head == None
def add(self, value):
"""
头部插法
先让新节点的next指向头节点
再将头节点替换为新节点
顺序不可错,要先保证原链表的链不断,否则头节点后面的链会丢失
"""
node = Node(value)
if self.is_empty():
self.__head = node
else:
node.next = self.__head
self.__head.prev = node
self.__head = node
def append(self, value):
"""
尾部插法
"""
node = Node(value)
cur = self.__head
if self.is_empty():
self.__head = node
else:
while cur.next:
cur = cur.next
cur.next = node
node.prev = cur
def insert(self, pos, value):
"""
指定位置插入元素
"""
# 应对特殊情况
if pos <= 0:
self.add(value)
elif pos > len(self) - 1:
self.append(value)
else:
node = Node(value)
prior = self.__head
count = 0
# 在插入位置的前一个节点停下
while count < (pos - 1):
prior = prior.next
count += 1
# 先将插入节点与节点后的节点连接,防止链表断掉,先链接后面的,再链接前面的
node.next = prior.next
# 将下一个的prev指向新节点
prior.next.prev = node
# 将新节点的prev指向prior
node.prev = prior
# 将prior的next指向新节点
prior.next = node
def remove(self, value):
"""
移除元素
"""
cur = self.__head
prior = None
while cur:
if value == cur.value:
# 判断此节点是否是头节点
if cur == self.__head:
self.__head = cur.next
else:
prior.next = cur.next
cur.next.prev = prior
break
# 还没找到节点,继续遍历
else:
prior = cur
cur = cur.next
def search(self, value):
"""
搜索元素
"""
cur = self.__head
while cur:
if value == cur.value:
return True
cur = cur.next
return False
def travel(self):
"""
遍历链表
"""
cur = self.__head
while cur:
print(cur.value)
cur = cur.next
if __name__ == "__main__":
link_list = BothWayLinkList()
link_list.append('a')
link_list.append('b')
link_list.append('d')
# link_list.insert(2, 'c')
link_list.travel()
print(len(link_list))
print(link_list.search(3))