232.用栈实现队列225.用队列实现栈

732 阅读1分钟

232.用栈实现队列

实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

class MyQueue {
    Stack<Integer> stackIn;
    Stack<Integer> stackOut;
    public MyQueue() {
        stackIn = new Stack<>();
        stackOut = new Stack<>();
    }    
    public void push(int x) {
        stackIn.push(x);
    }
    public int pop() {
        dumpstackIn();
        return stackOut.pop();
    }
    public int peek() {
        dumpstackIn();
        return stackOut.peek();
    }    
    public boolean empty() {
        return stackIn.isEmpty() && stackOut.isEmpty();
    }   
    public void dumpstackIn() {
        if(!stackOut.isEmpty()) return;
        while(!stackIn.isEmpty()){
            stackOut.push(stackIn.pop());
        }
    }
}

225.用队列实现栈

实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。

class MyStack {
    Deque<Integer> d1;
    public MyStack() {
        d1 = new ArrayDeque<>();
    }
    
    public void push(int x) {
        d1.addLast(x);
    }
    
    public int pop() {
        int size = d1.size();
        size--;
        while(size-- > 0){
            d1.addLast(d1.peekFirst());
            d1.pollFirst();            
        }
        int res = d1.pollFirst();
        return res;
    }
    
    public int top() {
        return d1.peekLast();
    }
    
    public boolean empty() {
        return d1.isEmpty();
    }
}