函数说明:
双链表的相关操作:
- 初始化;
- 判空;
- 求长度;
- 插入节点:头插、尾插、随机插入;
- 删除节点;
- 遍历节点;
- 查找节点(搜索节点);
代码:
class Node(object):
def __init__(self, elem):
self.elem = elem
self.prev = None
self.next = None
class DoubleLinkList(object):
"""双向循环链表"""
def __init__(self, node = None): # 和单链表一致
self.__head = node
def is_empty(self): # 和单链表一致
"""链表是否为空"""
return self.__head is None
def length(self): # 和单链表一致
# 游标用来遍历节点
cur = self.__head
# 节点计数器,初始值影响while循环的判断条件
counter = 0
while cur != None :
counter += 1
cur = cur.next
return counter
def travel(self): # 和单链表一致
cur = self.__head
while cur != None:
print(cur.elem)
cur = cur.next
def add(self, item):
"""链表头部添加元素"""
# print("=====头插法=====")
node = Node(item)
# 以下代码的顺序不唯一
node.next = self.__head
self.__head = node
node.next.prev = node
def append(self, item):
"""链表尾部添加元素"""
node = Node(item)
# print("=====尾插法=====")
# 特殊情况
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
node.prev = cur
def insert(self, pos, item):
"""
指定位置添加元素
@pos: 从0开始 例:insert(2,100)
"""
if pos <= 0 :
self.add(item)
elif pos > (self.length() - 1):
self.append(item)
else:
node = Node(item)
cur = self.__head
count = 0
while count < pos:
cur = cur.next
count += 1
# 当循环退出后,cur指向pos位置
node.next = cur
node.prev = cur.prev
cur.prev.next = node
cur.prev = node
def search(self, item): # 和单链表一致
"""查找节点是否存在"""
cur = self.__head
while cur != None:
if cur.elem == item:
return True
else:
cur = cur.next
return False
# 难度系数高
def remove(self, item):
cur = self.__head
while cur != None:
if cur.elem == item:
# 判断此节点是否为头节点
if cur == self.__head:
self.__head = cur.next
if cur.next:
# 链表是否只有一个节点
cur.next.prev = None
else:
cur.prev.next = cur.next
if cur.next:
# 不是尾节点
cur.next.prev = cur.prev
break
# pass
else:
cur = cur.next