日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python单链表操作_单链表的创建、增删改查等操作(Python实现)

發布時間:2024/10/12 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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实现)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。