题目来源:牛客网剑指offer

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

Python:42ms 5624k
# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    def push(self, node):
        self.stack1.append(node)
    def pop(self):
        if self.stack2:
            return self.stack2.pop()
        else:
            if not self.stack1:
                return None
            else:
                while self.stack1:
                    self.stack2.append(self.stack1.pop())
            return self.stack2.pop() 

C++:5ms 588k

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if (!stack2.empty()){
            int p = stack2.top();
            stack2.pop();
            return p;
        }
        else if (stack1.empty()){
            return NULL;
        }
        else{
            while (!stack1.empty()){
                stack2.push(stack1.top());
                stack1.pop();
            }
            int p = stack2.top();
            stack2.pop();
            return p;
        }
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

 

 

 
posted on 2018-05-23 15:29  想飞的萌猪  阅读(113)  评论(0编辑  收藏  举报