python 單鏈表

2021-06-06 00:15:41 字數 1537 閱讀 7883

class node:

def __init__(self, cargo = none, next = none):

self.cargo = cargo

self.next = next

def __str__(self):

return str(self.cargo)

node1 = node("one")

node2 = node("two")

node1.next = node2

node3 = node("three")

node2.next = node3

print (node1)

print (node2)

print (node3)

def printlist(anode):

head = anode

while head != none:

print (head)

head = head.next

print ("here we print our list from head to tail:")

printlist(node1)

def printbackward(anode):

if anode == none: # empty linked list

return

head = anode # head

tail = anode.next # others but head

printbackward(tail) # recursion

print (head) # print head

print ("here we print our list from tail to head:")

printbackward(node1)

def printbackwardbetter(anode):

if anode == none: # anode is none

return # end it

printbackwardbetter(anode.next) # recursion print

print (anode) # print anode

print ("here is better version:")

printbackwardbetter(node1)

def removesecond(list):

if list == none:

return

first = list

second = list.next

first.next = second.next

second.next = none

return second

print ("after remove second:")

removed = removesecond(node1)

printlist(node1)

input()

單鏈表 python

class node object def init self,item self.item item self.next none class singlelist object def init self self.head none def is empty self return self....

python 構造單鏈表

鍊錶 linked list 是由一組被稱為結點的資料元素組成的資料結構,每個結點都包含結點本身的資訊和指向下乙個結點的位址。由於每個結點都包含了可以鏈結起來的位址資訊,所以用乙個變數就能夠訪問整個結點序列。也就是說,結點包含兩部分資訊 一部分用於儲存資料元素的值,稱為資訊域 另一部分用於儲存下乙個...

python實現單鏈表

code python code coding utf 8 class node def init self,value self.data value self.next none class linklist def init self,data 0 self.head none self.in...