本題來自程序員代碼面試指南
編寫一個類掘殴,用兩個棧實現(xiàn)隊列,支持隊列的基本操作(add粟誓、poll奏寨、peek)
實現(xiàn)思路
一個棧作為壓入棧,在壓入數(shù)據(jù)時只往這個棧中壓入鹰服,記為stackPush病瞳;
另一個棧只作為彈出棧,在彈出數(shù)據(jù)時只從這個棧彈出悲酷,記為stackPop套菜。
實現(xiàn)這個有倆個關(guān)鍵點
- 1.如果stackPush要往stackPop中壓入數(shù)據(jù),那么必須一次性把stackPush中的數(shù)據(jù)全部壓入设易。
- 2.如果stackPop不為空逗柴,stackPush絕對不能向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<>();
}
/**
* 入隊操作
* 直接將數(shù)據(jù)壓入壓入數(shù)據(jù)棧
* @param push
*/
public void push(int push) {
this.stackPush.push(push);
}
/**
* 出隊操作
* @return
*/
public int poll() throws Exception {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new Exception("隊列中沒有數(shù)據(jù)");
} else if (stackPop.isEmpty()) {
//彈出數(shù)據(jù)棧為空顿肺,可以將整個壓入數(shù)據(jù)棧中的數(shù)據(jù)倒入彈出數(shù)據(jù)棧
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
/**
* 返回隊頭元素
* @return
* @throws Exception
*/
public int peek() throws Exception {
if (stackPush.isEmpty() && stackPop.isEmpty()) {
throw new Exception("隊列中沒有數(shù)據(jù)");
}else if (stackPop.isEmpty()) {
//彈出數(shù)據(jù)棧為空戏溺,可以將整個壓入數(shù)據(jù)棧中的數(shù)據(jù)倒入彈出數(shù)據(jù)棧
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}