剑指offer 用两个栈实现队列

题目

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路

用一个栈存储数据,另一个作为中转。

代码

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack = []
    def push(self, node):
        # write code here
        self.stack.append(node)
    def pop(self):
        # return xx
        tmp_stack = []
        while self.stack:
            tmp_stack.append(self.stack[-1])
            self.stack.pop(-1)
        res_node = tmp_stack[-1]
        tmp_stack.pop(-1)
        while tmp_stack:
            self.stack.append(tmp_stack[-1])
            tmp_stack.pop(-1)
        return res_node

猜你喜欢

转载自blog.csdn.net/y12345678904/article/details/80600933
今日推荐