双向链表
coding:utf-8
class Node(object):
“””生成双向链表的节点”””
def init(self, item):
self.item = item
self.next = None
self.prior = None
class DoubleLinkList(object):
“””双链表”””
def init(self, node=None):
self.__head = node # ****定义成私有的
def is_empty(self):
"""链表是否为空"""
return self.__head is None
def length(self):
"""链表长度"""
# cut游标,用来移动遍历结点
cur = self.__head
# count 记录数量
count = 0 # 注意这个是0
while cur is not None: # 不用cur.next,用的话最后一个就直接跳出,不执行加1了
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
cur = self.__head
while cur is not None:
print(cur.item, end=" ")
cur = cur.next
def add(self, item):
"""链表表头添加,头插法"""
node = Node(item)
if self.is_empty():
# 如果是空链表,将_head指向node
self._head = node
else:
# 将node的next指向_head的头节点
node.next = self._head
# 将_head的头节点的prev指向node
self._head.prior = node
# 将_head 指向node
self._head = node
def append(self, item):
"""尾插法"""
node = Node(item)
cur = self.__head # 从头往后走,走到最后
if self.__head is None: # 判断是否为空
self.__head = node
else:
while cur.next is not None: # 用的是cur.next
cur = cur.next # 往后移动
cur.next = node
node.prior = cur
def insert(self, pos, item):
"""指定位置添加元素
:param pos: 从0开始
:param item:
"""
if pos <= 0:
self.add(item)
elif pos > self.length():
self.append(item)
else:
cur = self.__head # 直接去找指的,不是__head
count = 0
while count < pos-1: # 不是小于等于,寻找前一个节点
cur = cur.next
count += 1
# 当循环退出后,prior指向pos位置
node = Node(item)
node.next = cur
node.prior = cur.prior
cur.prior.next = node
cur.prev = node
def remove(self, item):
"""删除结点
:param item:00
"""
cur = self.__head
while cur is not None:
if cur.item == item:
# 先判断是否是头结点
if cur is self.__head:
self.__head = cur.next
if cur.next:
# 判断链表是否只有一个结点
cur.next.prior = None
else:
cur.prior.next = cur.next
if cur.next: # 达到最后
cur.next.prior = cur.prior
# del cur
print("删除%d成功" % item)
break
else:
prior = cur
cur = cur.next
else:
print("没有这个元素,删除失败")
def search(self, item):
cur = self.__head
count = 0
if cur is None:
return print("空的,查找%d失败" % item)
else:
while cur is not None: # 是cur不是cur.next
if cur.item == item:
return count
else:
cur = cur.next
count += 1
print("查找%d失败,没有这个元素" % item)
if name == ‘main‘:
ll = DoubleLinkList()
print(ll.is_empty())
print(ll.length())
ll.add(0)
ll.append(1)
ll.append(2)
ll.append(5)
ll.append(3)
ll.add(20)
# 20 0 1 2 5 3
ll.insert(-1, 9)
ll.insert(3, 90)
# 9 20 0 90 1 2 5 3
ll.travel()
print("\n********************")
ll.search(3233)
ll.remove(5)
ll.travel()
转载请注明来源,欢迎指出任何有错误或不够清晰的表达。可以邮件至gxnucgb@qq.com
文章标题:双向链表
文章字数:665
本文作者:陈桂彬
发布时间:2019-08-11, 22:28:24
最后更新:2019-08-13, 16:23:20
原始链接:https://github.com/gxnucgb/gxnucgb.github.io/2019/08/11/双向链表/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。