python单链表实现具体例子_Python实现数据结构线性链表(单链表)算法示例
本文實例講述了Python實現數據結構線性鏈表(單鏈表)算法。分享給大家供大家參考,具體如下:
初學python,拿數據結構中的線性鏈表存儲結構練練手,理論比較簡單,直接上代碼。
#!/usr/bin/python
# -*- coding:utf-8 -*-
# Author: Hui
# Date: 2017-10-13
# 結點類,
class Node:
def __init__(self, data):
self.data = data # 數據域
self.next = None # 指針域
def get_data(self):
return self.data
# 鏈表類
class List:
def __init__(self, head):
self.head = head # 默認初始化頭結點
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): # 追加結點(鏈表尾部追加)
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
def delete(self, index): # 刪除結點
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): # 插入結點
if pos < 1 or pos > self.get_len():
print "插入結點位置不合理..."
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): # 反轉鏈表
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 '初始化頭結點:\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個元素:\t',list.print_list(head)
node = Node("insert")
list.insert(3, node)
print '第3個位置插入‘insert'字符串 :\t', list.print_list(head)
head = list.reverse(head)
print '鏈表反轉:', list.print_list(head)
執行結果:
希望本文所述對大家Python程序設計有所幫助。
總結
以上是生活随笔為你收集整理的python单链表实现具体例子_Python实现数据结构线性链表(单链表)算法示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++中outtextxy_第12章 坚
- 下一篇: 计算机有必要报英语四级吗,我已工作了,现