您的位置:首页 > 其它

用栈实现队列(每日一道算法题)

2017-11-22 15:17 330 查看
用两个栈实现队列,支持列的基本操作(add,poll,peek)

package stack;

import java.util.Stack;

/**
* @author:MindMrWang
*2017年11月14日
*要求:*用两个栈实现队列,支持列的基本操作(add,poll,peek)*
*:function:用两个栈实现一个队列
*可以将一个栈设为主栈,另外一个栈设置为传输栈,先将数放入传输栈,然后再将数放入主栈
*/
public class twoStacksQueue {
private Stack<Integer> stackMain;
private Stack<Integer> stackTransfer;
public twoStacksQueue() {
this.stackMain = new Stack<Integer>();
this.stackTransfer = new Stack<Integer>();

}

public int peak() {
if(stackMain.isEmpty()&&stackTransfer.isEmpty()) {
throw new RuntimeException("your queue is empty");
}else if(stackMain.isEmpty()){
while(!stackTransfer.isEmpty()) {
stackMain.push(stackTransfer.pop());
}
}
return stackMain.peek();
}
public int poll() {
if(stackMain.isEmpty()&&stackTransfer.isEmpty()) {
throw new RuntimeException("your queue is empty");
}else if(stackMain.isEmpty()){
while(!stackTransfer.isEmpty()) {
stackMain.push(stackTransfer.pop());
}
}
return stackMain.pop();

}

public void add(int newNum) {
this.stackTransfer.push(newNum);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: