剑指offer66题--Java实现,c++实现和python实现 5.用两个栈实现一个队列

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

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

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

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

Java实现

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
     
    public void push(int node) {
        stack1.push(node);
    }
     
    public int pop() {
        if(stack1.empty()&&stack2.empty()){
            throw new RuntimeException("Queue is empty!");
        }
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

python实现

class Solution:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []
    def push(self, node):
        self.stack1.append(node)
    def pop(self):
        if len(self.stack2) != 0:
            return self.stack2.pop()
        while len(self.stack1) !=0:
            self.stack2.append(self.stack1.pop())
 
        return self.stack2.pop()

猜你喜欢

转载自blog.csdn.net/walter7/article/details/84290501