单链表的创建、增删改查等操作(Python实现)
# 单链表
class Node:
def __init__(self, elem):
self.elem = elem
self.next = None
class SingleLinkedList:
def __init__(self, length):
self.head = Node(length)
self.end = self.head
def length(self):
# 求链表长度
cur = self.head
count = 0
while cur.next :
count += 1
cur = cur.next
return count
def isempty(self):
# 判断链表是否为空
return self.head.next == None
def add(self, elem):
# 头插法
node = Node(elem)
node.next = self.head.next
self.head.next = node
def append(self, elem):
# 尾插法
node = Node(elem)
node.next = None
self.end.next = node
self.end = node
def insert(self, loc, elem):
# 向链表第loc位置插入 数据域 为elem的结点
cur = self.head
count = 0
while cur and count
cur = cur.next
count += 1
if not cur or count>loc-1:
print("插入失败")
return
node = Node(elem)
node.next = cur.next
cur.next = node
def remove(self, loc):
# 删除链表第loc位置结点
cur = self.head
count = 0
while cur.next and count
cur = cur.next
count += 1
if not cur.next or count>loc-1:
print("删除操作不合法")
return
cur.next = cur.next.next
def travel(self):
# 遍历链表
cur = self.head
while cur.next:
cur = cur.next
print(cur.elem)
if self.isempty():
print("该链表为空")
def getelem(self, loc):
# 获取第loc位置的结点的数据域
cur = self.head.next
count = 1
while cur and count
cur = cur.next
count += 1
if not cur or count>loc :
print("不存在")
return
print(cur.elem)
def search(self, elem):
# 查询链表中 数据域 为elem的结点 第一次出现的位置
cur = self.head.next
while cur and cur.elem!=elem:
cur = cur.next
if cur and cur.elem==elem:
print(cur)
return
print("不存在")
pass
def main():
length = 0
sll = SingleLinkedList(length)
print(sll.isempty())
print(sll.length())
sll.append(1)
sll.append(2)
sll.append(3)
sll.append(4)
sll.append(5)
print(sll.length())
sll.travel()
main()
点赞
收藏
分享
文章举报
Yes ,I can !
发布了16 篇原创文章 · 获赞 1 · 访问量 367
私信
关注