【DataStructure In Python】Python模拟栈和队列
用Python模拟栈和队列主要是利用List,当然也可以使用collection的deque。
以下内容为栈:
#! /usr/bin/env python # DataStructure Stack class Stack: def __init__(self, data=None): if data is not None: self.stk = [data] self.top = 0 else: self.stk = [] self.top = -1 def __str__(self): return " ".join([str(x) for x in self.stk]) def push(self, data): self.stk.append(data) self.top += 1 def pop(self): if self.top == -1: print "Stack is empty" return return self.stk.pop() def isEmpty(self): if self.top == -1: return 1 else : return 0 if __name__ == "__main__": stack = Stack() for i in range(10): stack.push(i) print "push:",stack print "pop: ", for i in range(3): print stack.pop(), print "" print "left:",stack
以下内容为队列:
#! /usr/bin/env python # DataStructure Queue class Queue: def __init__(self, data=None): if data is not None: self.que = [data] else: self.que = [] def __str__(self): return " ".join([str(x) for x in self.que]) def isEmpty(self): if len(self.que): return 0 else: return 1 def enQueue(self, data): self.que.append(data) def deQueue(self): return self.que.pop(0) if __name__ == "__main__": queue = Queue() for i in range(10, 0, -1): queue.enQueue(i) print "enQueue:",queue print "deQueue:", for i in range(3): print queue.deQueue(), print "" print "left: ",queue