题目描述

用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。

解析:

	Stack<Integer> in = new Stack<Integer>();
	Stack<Integer> out = new Stack<Integer>();
    public void push(int node) { 
      in.push(node);
  }
 	public int pop() throws Exception { 
 		if (out.isEmpty()){
	  	  while (!in.isEmpty()) {
      		out.push(in.pop()); 
      }
    }
  		if (out.isEmpty())
 		  throw new Exception("queue is empty"); 
    return out.pop(); 
  }

题目描述

用两个队列来实现一个栈,完成栈的 Push 和 Pop 操作。

解析:这里只用了一个队列

class MyStack {
	 private Queue<Integer> queue;
 	 public MyStack() { 
 		 queue = new LinkedList<>(); 
 	 }
  	public void push(int x) {
  		 queue.add(x); 
   		int cnt = queue.size();
    	while (cnt-- > 1) {
    	 queue.add(queue.poll()); 
    	 } 
     }
     public int pop() {
     	return queue.remove(); 
     }
     public int top() { 
     	return queue.peek(); 
     }
     public boolean empty() { 
    	 return queue.isEmpty(); 
     }
   }