通过两个队列实现栈
队列实现栈

public class TwoQueueAsStack {

	Queue<Integer> data;
	Queue<Integer> help;
	public TwoQueueAsStack() {
		data=new LinkedList<>();
		help=new LinkedList<>();
	}
	public Integer pop() {
		if(data.isEmpty())
			return null;
		while(data.size()>1)
			help.add(data.poll());
		int res=data.poll();
		swap();
		return res;
	}
	public void push(Integer num) {
		data.add(num);
	}
	public Integer peek() {
	if(data.isEmpty())
		throw new RuntimeException("Stack is empty");
	while(data.size()>1)
		help.add(data.poll());
	int res=data.poll();
	help.add(res);
	swap();
	return res;
	}
	public void swap() {
		Queue<Integer> tmp=data;
		data=help;
		help=tmp;
	}
	public static void main(String[] args) {
		TwoQueueAsStack stack=new TwoQueueAsStack();
		stack.push(2);
		stack.push(3);
		stack.push(1);
		System.out.println(stack.peek());
		System.out.println(stack.pop());
		System.err.println(stack.peek());
		System.err.println(stack.peek());
	}

}

相关文章:

  • 2021-12-11
  • 2021-07-31
  • 2021-11-08
  • 2022-12-23
  • 2021-08-23
  • 2021-09-04
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-07
  • 2021-08-06
  • 2021-12-11
  • 2022-12-23
相关资源
相似解决方案