Python单链表的基本操作
程序员文章站
2022-05-13 11:38:00
链表的基本操作"""初始化链表"""import timeclass Node: def __init__(self,value): self.value = value self.next = Noneclass SingleLinkList: def __init__(self): self.head = None def is_empty(self): """判断是否为空""" r...
单链表的基本操作
"""
初始化链表
"""
import time
class Node:
def __init__(self,value):
self.value = value
self.next = None
class SingleLinkList:
def __init__(self):
self.head = None
def is_empty(self):
"""判断是否为空"""
return self.head == None
def travel(self):
"""遍历链表"""
cur = self.head
while cur is not None:
print(cur.value,end=" ")
cur = cur.next
def append(self,item):
"""在末尾添加节点"""
node = Node(item)
# 如果是空链表
if self.is_empty():
self.head = node
return
# 当不为空的时候
cur = self.head
while cur.next:
cur = cur.next
cur.next = node
# node.next = None
def insert(self,index,item):
"""插入中间节点"""
if (self.head is None) and (self.head.next is None):
return
cur = self.head
while cur is not None and index > 1:
index = index - 1
cur = cur.next
node = Node(item)
node.next = cur.next
cur.next = node
def add(self,item):
"""在头部添加节点"""
node = Node(item)
node.next = self.head
self.head = node
def length(self):
"""获取链表的长度"""
cur = self.head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def search(self,item):
# 查看item在链表中是否存在
cur = self.head
while cur != None:
if cur.value == item:
return True
else:
cur = cur.next
return False
def pop_last(self):
"""弹出链表的最后一个元素"""
if self.head is None:
return
cur = self.head
if cur.next is None:
self.head = None
return
while cur.next.next is not None:
cur = cur.next
cur.next = None
def pop_head(self):
"""把链表的第一个元素弹出"""
if self.head is None:
return
self.head = self.head.next
def cycle(self):
"""循环输出链表"""
cur = self.head
if cur.next == None:
cur.next = self.head
while cur.next != None:
self.travel()
time.sleep(3)
if __name__ == '__main__':
s = SingleLinkList()
s.append(100)
s.append(300)
s.append(600)
s.add(500)
s.add(150)
head = Node(30)
head.next = Node(40)
head.next.next = Node(50)
s.pop_head()
s.pop_last()
s.cycle()
s.travel()
本文地址:https://blog.csdn.net/weixin_46120601/article/details/107553124
推荐阅读
-
详解python中的 is 操作符
-
opencv-python教程学习系列7-opencv图像基本操作
-
队列基本概念及顺序队列上的操作
-
分享Python中list的各项操作技巧
-
基于python的Opencv项目实战 (一)图像基本操作
-
opencv新手入门----图像的基本操作(一)
-
线性表的链式存储结构:定义、单链表存储结构、给链表头结点分配空间、初始化链表数据、输出链表、在某个位置上插入数据、头插法、尾插法、删除某个位置上的数据、删除某个数据、删除整个链表计算链表的长度
-
Python实现的tab文件操作类分享
-
Python下如何实现文件的修改操作?(附示例)
-
python中关于前后缀操作的详解