由两个栈组成的队列【Java】

由两个栈组成的队列

【Day_02】
【题目描述】

编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)

【解题思路】

队列的特点是先进先出,栈的特点是先进后出,这里可以通过一个压入栈和一个弹出栈配合实现,压入操作只对压入栈,弹出操作时将压入的数据压入弹出栈,然后弹出就可以实现了。

但是其中要遵循两个原则:

1.向弹出栈压入的时候必须一次性压入。

2.弹出栈中不为空时,不能压入元素。

【代码】
import java.util.Stack;

public class StackQueue {
	Stack<Integer> stackPush;
	Stack<Integer> stackPop;
	
	public StackQueue() {
		stackPush=new Stack<Integer>();
		stackPop=new Stack<Integer>();
	}
	
	public void add(int x) {
		stackPush.push(x);
	}
	
	public int poll() {
		if(stackPush.empty()&&stackPop.empty()) {
			new RuntimeException("Empty");
		}else if(stackPop.empty()) {
			while(!stackPush.empty()) {
				stackPop.push(stackPush.pop());
				}
		}
		return stackPop.pop();
	}
	
	public int peek() {
		if(stackPush.empty()&&stackPop.empty()) {
			new RuntimeException("Empty");
		}else if(stackPop.empty()) {
			while(!stackPush.empty()) {
			stackPop.push(stackPush.pop());
			}
		}
		return stackPop.peek();
	}
	
}

发布了58 篇原创文章 · 获赞 5 · 访问量 6297

猜你喜欢

转载自blog.csdn.net/weixin_40992982/article/details/101346157