双向链表
# doublelinklist
class Node(object):
"""节点"""
def __init__(self, item):
# 记录数据内容
self.item = item
# 记录下一个节点
self.next = None
# 记录前置节点
self.pre = None
class DoubleLinkList(object):
"""双向链表"""
def __init__(self):
# 记录头节点,所有的操作从头节点开始
self.__head = None
def is_empty(self):
"""链表是否为空"""
# 判断头节点是否为空
return self.__head is None
def length(self):
"""链表长度"""
if self.is_empty():
return 0
# 定义count 累计加1
count = 0
# 从头到尾遍历
cur = self.__head
while cur is not None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
if self.is_empty():
return
# 定义游标,从头往后移动
cur = self.__head
while cur is not None:
print(cur.item, end=" ")
cur = cur.next
print()
def add(self, item):
"""链表头部添加元素"""
# 创建新节点
node = Node(item)
# 判断链表是否为空
if self.is_empty():
self.__head = node
return
# 让新节点的next指向原来的头
node.next = self.__head
# 让原来的头节点的pre指向新节点
self.__head.pre = node
# 让head记录新节点
self.__head = node
def append(self, item):
"""链表尾部添加元素"""
# 判断头节点是否为空
if self.is_empty():
self.add(item)
return
# 从头遍历,找到尾节点
cur = self.__head
while cur.next is not None:
cur = cur.next
# 当while循环结束,cur指向的是尾节点
node = Node(item)
cur.next = node
# 让新节点的pre指向原来的尾节点
node.pre = cur
def insert(self, pos, item):
"""指定位置添加元素"""
# 健壮性
if pos <= 0:
self.add(item)
elif pos >= self.length():
self.append(item)
else:
# 从头遍历,找到pos前面的节点
cur = self.__head
# 定义下标,index记录的是当前cur指向的对象的下标
index = 0
while index < (pos - 1):
index += 1
cur = cur.next
# while循环结束,cur执行的是pos前面的节点
node = Node(item)
node.next = cur.next
# 原来位置节点的pre记录节点
cur.next.pre = node
cur.next = node
# 新节点的pre记录pos前面的节点
node.pre = cur
def remove(self, item):
"""删除节点"""
# 从头遍历,找到要删除的节点
cur = self.__head
while cur is not None:
if cur.item == item:
# 如果cur.pre为空,证明删除的头节点
if cur.pre is None:
self.__head = cur.next
else:
cur.pre.next = cur.next
# 如果cur.next为空,证明删掉的是尾节点
if cur.next is not None:
cur.next.pre = cur.pre
return
cur = cur.next
def search(self, item):
"""查找节点是否存在"""
if self.is_empty():
return False
cur = self.__head
while cur is not None:
if cur.item == item:
return True
cur = cur.next
# while循环结束,没找到
return False
if __name__ == '__main__':
sll = DoubleLinkList()
print(sll.is_empty())
print(sll.length())
sll.add(3)
sll.add(2)
sll.add(1)
print(sll.is_empty())
print(sll.length())
sll.travel()
sll.add(4)
sll.travel()
print(sll.length())
sll.append(5)
sll.travel()
sll.insert(2,6)
sll.travel()
sll.insert(4, 7)
sll.travel()
sll.insert(-100, 8)
sll.insert(100, 9)
sll.travel()
sll.remove(6)
sll.remove(8)
sll.remove(9)
sll.travel()
print(sll.search(4))
print(sll.search(2))
print(sll.search(5))
print(sll.search(6))