最近在看算法相关的知识, 顺便复习下python, 就用python来写算法吧, 开始!
题目1: 用两个栈实现一个队列, 分别在队列尾部插入节点和在队列头部删除节点
解答:
#!/usr/bin/python# use two stacks to implement a queueclass MyQueue(object): """docstring for MyQueue""" def __init__(self, arg): super(MyQueue, self).__init__() self.arg = arg self.stack1 = [] self.stack2 = [] def appendTail(self, number): self.stack1.append(number) def deleteHead(self): if len(self.stack2) > 0: print self.stack2.pop() else: while len(self.stack1) > 0: self.stack2.append(self.stack1.pop()) print self.stack2.pop() def printQueue(self): print self.stack1 print self.stack2 def main(): test = MyQueue("test") test.appendTail(1) test.appendTail(2) test.appendTail(3) test.appendTail(4) test.deleteHead() test.deleteHead() test.printQueue()if __name__ == '__main__': main()