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 单链表
最新推荐文章于 2022-04-02 15:01:29 发布