python 单链表

来源:互联网 发布:游族网络公告 编辑:程序博客网 时间:2024/04/30 10:24
class Node:def __init__(self, cargo = None, next = None):self.cargo = cargoself.next = nextdef __str__(self):return str(self.cargo)node1 = Node("one")node2 = Node("two")node1.next = node2node3 = Node("three")node2.next = node3print (node1)print (node2)print (node3)def printlist(anode):head = anodewhile head != None:print (head)head = head.nextprint ("Here we print our list from head to tail:")printlist(node1)def printBackward(anode): if anode == None: # empty linked listreturn head = anode       # headtail = anode.next  # others but headprintBackward(tail) # recursionprint (head)        # print headprint ("Here we print our list from tail to head:")printBackward(node1)def printBackwardbetter(anode):if anode == None:  # anode is Nonereturn          # end itprintBackwardbetter(anode.next)  # recursion printprint (anode)       # print anodeprint ("Here is better version:")printBackwardbetter(node1)def removeSecond(list):if list == None:return first = listsecond = list.nextfirst.next = second.nextsecond.next = Nonereturn secondprint ("After remove second:")removed = removeSecond(node1)printlist(node1)input()