两个栈实现一个队列结构python实现

#File Name : 栈实现队列.py

class twostackqueue(object):
    def __init__(self):
        self.push_stack = []
        self.pop_stack = []

    def push(self,item):
        self.push_stack.append(item)
        print(self.push_stack)


    def pop(self):
        if len(self.push_stack)<1 and len(self.pop_stack)<1:
            raise Exception('empty')
        elif len(self.pop_stack)<1:
            while len(self.push_stack)>0:
                self.pop_stack.append(self.push_stack.pop())
        res = self.pop_stack.pop()

        return res

    def peek(self):
        if len(self.push_stack)<1 and len(self.pop_stack)<1:
            raise Exception('empty')
        elif len(self.pop_stack)<1:
            while len(self.push_stack)>0:
                self.pop_stack.append(self.push_stack.pop())
        return self.pop_stack[-1]

if __name__ == '__main__':
    a = twostackqueue()

    a.push(1)
    a.push(2)
    a.push(3)
    a.push(4)
    a.push(5)
    c = a.pop()
    print(c)
    d = a.peek()
    print(d)

 

你可能感兴趣的:(算法牛人之路)