本題來自程序員代碼面試指南
編寫一個(gè)類,用兩個(gè)棧實(shí)現(xiàn)隊(duì)列,支持隊(duì)列的基本操作(add、poll、peek)
實(shí)現(xiàn)思路
一個(gè)棧作為壓入棧,在壓入數(shù)據(jù)時(shí)只往這個(gè)棧中壓入,記為stackPush;
另一個(gè)棧只作為彈出棧,在彈出數(shù)據(jù)時(shí)只從這個(gè)棧彈出,記為stackPop。
實(shí)現(xiàn)這個(gè)有倆個(gè)關(guān)鍵點(diǎn)
- 1.如果stackPush要往stackPop中壓入數(shù)據(jù),那么必須一次性把stackPush中的數(shù)據(jù)全部壓入。
- 2.如果stackPop不為空,stackPush絕對(duì)不能向stackPop中壓入數(shù)據(jù)。
java Stack類中的isEmpty()和empty()的區(qū)別
public class TwoStacksQueue {
private Stack<Integer> stackPush;//壓入數(shù)據(jù)棧
private Stack<Integer> stackPop; //彈出數(shù)據(jù)棧
public TwoStacksQueue() {
this.stackPop = new Stack<>();
this.stackPush = new Stack<>();
}
/**
* 入隊(duì)操作
* 直接將數(shù)據(jù)壓入壓入數(shù)據(jù)棧
* @param push
*/
public void push(int push) {
this.stackPush.push(push);
}
/**
* 出隊(duì)操作
* @return
*/
public int poll() throws Exception {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new Exception("隊(duì)列中沒有數(shù)據(jù)");
} else if (stackPop.isEmpty()) {
//彈出數(shù)據(jù)棧為空,可以將整個(gè)壓入數(shù)據(jù)棧中的數(shù)據(jù)倒入彈出數(shù)據(jù)棧
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
/**
* 返回隊(duì)頭元素
* @return
* @throws Exception
*/
public int peek() throws Exception {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new Exception("隊(duì)列中沒有數(shù)據(jù)");
}else if (stackPop.isEmpty()) {
//彈出數(shù)據(jù)棧為空,可以將整個(gè)壓入數(shù)據(jù)棧中的數(shù)據(jù)倒入彈出數(shù)據(jù)棧
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}