1. 程式人生 > >python實現棧和隊列

python實現棧和隊列

隊列 tac class sta python實現 body ret none !=

class Node:#節點類
next = None#節點指針指向下一個
def __init__(self,data):
self.data=data
------------------------------------------
class Queue:
first = Node(None)#頭節點
last = Node(None)#尾節點
def inQueue(self,node):#進隊列
if self.first.data==None:
self.first = node
self.last = node
else:
self.last.next = node
self.last = node
def deQueue(self):#出隊列
node = self.first
self.first = self.first.next
return node
q = Queue()#創建隊列對象
q.inQueue(Node(1))#進隊
q.inQueue(Node(2))#進隊
n = q.deQueue()#出隊
m = q.deQueue()#出隊
print n.data,m.data
--------------------------------

class Stack:#棧
top = Node(None)
def add(self,node):#進棧
node.next=self.top
self.top = node
def out(self):#出棧
node =self.top
while node.data!=None:
print node.data,
node= node.next
s =Stack()
s.add(Node(1))#進棧
s.add(Node(2))#進棧
s.add(Node(3))#進棧
s.out()#出棧

python實現棧和隊列