#!/usr/bin/python3
#建立双向链表。
class Node():
def __init__(self,data=None):
self.data=data
self.next=None
self.previous=None
class DoubleLinkedList():
def __init__(self):
self.head=None
self.tail=None
def addDoubleList(self,newNode):
if isinstance(newNode,Node):
if self.head==None:
self.head=newNode
newNode.previous=None
newNode.next=None
self.tail=newNode
else:
self.tail.next=newNode
newNode.previous=self.tail
self.tail=newNode
return
def printListFromHead(self):
ptr=self.head
while ptr:
print(ptr.data)
ptr=ptr.next
def printListFromTail(self):
ptr=self.tail
while ptr:
print(ptr.data)
ptr=ptr.previous
doubleLink=DoubleLinkedList()
n1=Node(5)
n2=Node(15)
n3=Node(25)
for n in [n1,n2,n3]:
doubleLink.addDoubleList(n)
print("从头部打印双向链表")
doubleLink.printListFromHead()
print("从尾部打印双向链表")
doubleLink.printListFromTail()
Python语言例题集(014)
于 2024-05-26 23:51:40 首次发布