python单链表操作_单链表的创建、增删改查等操作(Python实现)
單鏈表的創建、增刪改查等操作(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
私信
關注
總結
以上是生活随笔為你收集整理的python单链表操作_单链表的创建、增删改查等操作(Python实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是货币基金
- 下一篇: python 海象运算符,Python3