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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python单链表实现具体例子_Python实现数据结构线性链表(单链表)算法示例

發(fā)布時(shí)間:2025/3/11 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python单链表实现具体例子_Python实现数据结构线性链表(单链表)算法示例 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文實(shí)例講述了Python實(shí)現(xiàn)數(shù)據(jù)結(jié)構(gòu)線性鏈表(單鏈表)算法。分享給大家供大家參考,具體如下:

初學(xué)python,拿數(shù)據(jù)結(jié)構(gòu)中的線性鏈表存儲(chǔ)結(jié)構(gòu)練練手,理論比較簡單,直接上代碼。

#!/usr/bin/python

# -*- coding:utf-8 -*-

# Author: Hui

# Date: 2017-10-13

# 結(jié)點(diǎn)類,

class Node:

def __init__(self, data):

self.data = data # 數(shù)據(jù)域

self.next = None # 指針域

def get_data(self):

return self.data

# 鏈表類

class List:

def __init__(self, head):

self.head = head # 默認(rèn)初始化頭結(jié)點(diǎn)

def is_empty(self): # 空鏈表判斷

return self.get_len() == 0

def get_len(self): # 返回鏈表長度

length = 0

temp = self.head

while temp is not None:

length += 1

temp = temp.next

return length

def append(self, node): # 追加結(jié)點(diǎn)(鏈表尾部追加)

temp = self.head

while temp.next is not None:

temp = temp.next

temp.next = node

def delete(self, index): # 刪除結(jié)點(diǎn)

if index < 1 or index > self.get_len():

print "給定位置不合理"

return

if index == 1:

self.head = self.head.next

return

temp = self.head

cur_pos = 0

while temp is not None:

cur_pos += 1

if cur_pos == index-1:

temp.next = temp.next.next

temp = temp.next

def insert(self, pos, node): # 插入結(jié)點(diǎn)

if pos < 1 or pos > self.get_len():

print "插入結(jié)點(diǎn)位置不合理..."

return

temp = self.head

cur_pos = 0

while temp is not Node:

cur_pos += 1

if cur_pos == pos-1:

node.next = temp.next

temp.next =node

break

temp = temp.next

def reverse(self, head): # 反轉(zhuǎn)鏈表

if head is None and head.next is None:

return head

pre = head

cur = head.next

while cur is not None:

temp = cur.next

cur.next = pre

pre = cur

cur = temp

head.next = None

return pre

def print_list(self, head): # 打印鏈表

init_data = []

while head is not None:

init_data.append(head.get_data())

head = head.next

return init_data

if __name__ == '__main__':

head = Node("head")

list = List(head)

print '初始化頭結(jié)點(diǎn):\t', list.print_list(head)

for i in range(1, 10):

node = Node(i)

list.append(node)

print '鏈表添加元素:\t', list.print_list(head)

print '鏈表是否空:\t', list.is_empty()

print '鏈表長度:\t', list.get_len()

list.delete(9)

print '刪除第9個(gè)元素:\t',list.print_list(head)

node = Node("insert")

list.insert(3, node)

print '第3個(gè)位置插入‘insert'字符串 :\t', list.print_list(head)

head = list.reverse(head)

print '鏈表反轉(zhuǎn):', list.print_list(head)

執(zhí)行結(jié)果:

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

總結(jié)

以上是生活随笔為你收集整理的python单链表实现具体例子_Python实现数据结构线性链表(单链表)算法示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。