用两个栈实现一个队列
栈为后来居上,先进后出的数据结构,而队列为先进先出,可以用两个栈实现队列的特性:
- 申请两个栈:
stackPush和stackPop。
stackPush用来“压数”,就和普通的栈一样的作用
stackPop实现stackPush内元素的倒序,用以实现先进先出- 队列的
add()方法,即stackPush.push()- 队列的
poll()和peek()则要依赖stackPop,具体如下:
poll()时,如果stackPop为空,则从stackPush内逐一出栈然后压入stackPop中【及实现了stackPush内元素的倒序
- 如
stackPop不为空,则直接从stackPop出栈
peek()的实现同理
代码实现如下:
package com.lilydedbb;
import java.util.Stack;
/**
* Created by dbb on 2016/12/23.
*/
public class TwoStackQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackQueue(){
this.stackPush = new Stack<Integer>();
this.stackPop = new Stack<Integer>();
}
public void add(int newNumber){
this.stackPush.push(newNumber);
}
public int poll(){
if(this.stackPop.isEmpty() && this.stackPush.isEmpty()){
throw new RuntimeException("The Queue is empty");
}else if(this.stackPop.isEmpty()){
while (!this.stackPush.isEmpty())
this.stackPop.push(this.stackPush.pop());
}
return this.stackPop.pop();
}
public int peek(){
if(this.stackPop.isEmpty() && this.stackPush.isEmpty()){
throw new RuntimeException("The Queue is empty");
}else if(this.stackPop.isEmpty()){
while (!this.stackPush.isEmpty())
this.stackPop.push(this.stackPush.pop());
}
return this.stackPop.peek();
}
}
本文介绍如何利用两个栈的数据结构实现队列的功能,详细阐述了在入队、出队操作中栈的作用,以及如何通过栈的特性达到先进先出的效果,并提供了相应的代码实现。
425

被折叠的 条评论
为什么被折叠?



