61. Implement Stack using Queues

mplement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

push(x) 入栈:往非空队列的队尾插入元素。

pop() 删除栈顶元素:非空队列的末尾元素应该是需要被弹栈的元素。那么首先把非空队列的前n-1个元素移到另一个空队列中,然后删除剩余的那个元素即可。

top() 返回栈顶元素:非空队列的末尾元素应该是需要被返回的元素。那么首先把非空队列的元素移到另一个空队列中,注意保存第n个元素。

empty() 判断栈是否为空:两个队列同时为空时栈为空。

import java.util.concurrent.ArrayBlockingQueue;
class MyStack {
    
    	Queue<Integer> Q1 = new ArrayBlockingQueue<Integer>(10);
	Queue<Integer> Q2 = new ArrayBlockingQueue<Integer>(10);
	
	/*
     * 往非空的那个队列中添加元素。
     */
    public void push(int node) {
    	if(!Q1.isEmpty()){
    		Q1.add(node);
    	}else{
    		Q2.add(node);
    	}
    //	System.out.println(Q2);
    }
    /*
     * 出栈操作相当于弹出非空队列的队尾元素。
     * 那么首先把非空队列的前n-1个元素移到另一个空队列中,然后弹出剩余的那个元素即可
     */
    public void pop() {
    	if(!Q1.isEmpty()){
    		while(Q1.size()>1){
    			int node = Q1.poll();
    			Q2.add(node);
    		}
    	 Q1.poll();
    	}else{
    		while(Q2.size()>1){
    			int node = Q2.poll();
    			Q1.add(node);
    		}
    		Q2.poll();
    	}
    }
    
    // Get the top element.
    public int top() {
    int node = 0;
    	if(!Q1.isEmpty()){
    		while(Q1.size()>0){
    			node = Q1.poll();
    			Q2.add(node);
    		}
    		
    		return node;
    	}else{
    		while(Q2.size()>0){
    			node = Q2.poll();
    			Q1.add(node);
    		}
    		
    		return node;
    	}
    }

    // Return whether the stack is empty.
    public boolean empty() {
        return Q1.isEmpty() && Q2.isEmpty();
    }
    
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值