我们知道,“栈”是一种“后进先出”的数据结构,而“队列”的数据结构特点是“先进先出”,但我们可以通过自己构造一个方法,在方法内部使用“栈”来实现“队列”,以下为具体的实现思路。
首先,因为栈的数据结构特点“后进后出”不可改变,要使用栈实现队列“先进先出”的数据特点,在方法中,我们必须要使用两个栈才能够模拟队列,为了方便区分,我们给两个栈分别取名为“in”和“out”。
private Stackin=new Stack ();//入栈队 private Stack out=new Stack ();//出栈队
然后,我们来用这两个栈模拟队列的入队操作,提供offer()方法来实现入队操作,当in和out两个栈都为空的时候,我们就可以直接使用in这个栈的push()方法实现入队的操作,如果,out栈中还有数据,利用栈后进先出的特点,我们可以使用out这个栈的pop()方法将out栈中的数据存到in栈中,此时就能模拟队列入栈。
public void offer(E e) {
while(!out.empty()) {
in.push(out.pop());
}
in.push(e);
}
接着,就是模拟队列的出队操作,提供poll()方法来实现出队操作,因为当数据从in栈中出栈时,是从栈顶元素开始出栈的,为了实现先进先出,我们让数据从in栈中出栈后,再进入out栈中,接着从out栈中出栈,这样就能够模拟队列的出栈操作了。
public E poll(){
while(!in.empty()) {
out.push(in.pop());
}
return out.pop();
}
最后,为了实现遍历这个模拟队列,我们还需要添加一个isEmpty()方法,用来判断模拟队列为空,其实就是判断in和out这两个栈是否为空。
public boolean isEmpty() {
return in.size()==0&&out.size()==0;
}
这样,我们就实现了用栈模拟队列的操作,我们在主函数中进行调试。
MyQueuequeue=new MyQueue (); queue.offer("A1"); queue.offer("A2"); queue.offer("A3"); queue.offer("A4"); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll());
运行结果如下
A1 A2 A3 A4
遍历队列如下
while(!queue.isEmpty()) {
System.out.println(queue.poll());
}
A1
A2
A3
A4



