無論如果 StackA(最開始add元素的那個堆疊) 要往 StackB 中壓入元素,那么必須選擇一次性全部壓入。
無論什么時候從佇列中取元素,必須保證元素是從 StackB 中 pop 出的,也就是說,當 StackB 不為空的時候絕不能再次向 StackB 中壓入元素。
也就是在存入元素一直往 StackA 中存,取元素是從 StackB 中取,但要要注意的是取的時候需要保證 StackB 為空的時候要先將 StackA 中元素一次性壓如 StackB 中,在進行從 StackB 中取的操作。
public static class TwoStackQueue<E>{
private Stack<E> stackA;
private Stack<E> stackB;
public TwoStackQueue() {
stackA = new Stack<>();
stackB = new Stack<>();
}
/**
* 添加元素邏輯
* @param e 要添加的元素
* @return 這里只是遵循 Queue 的習慣,這里簡單處理回傳 true 即可
*/
public boolean add(E e){
stackA.push(e);
return true;
}
/**
* 去除元素的時候需要判斷兩個地方,StackA & StackB 是否都為空
* StackB 為空的時候講StackA中的元素全部依次壓入 StackB
* @return 回傳佇列中的元素 如果佇列為慷訓傳 null
*/
public E poll(){
//如果佇列中沒有元素則直接回傳空,也可以選擇拋出例外
if (stackB.isEmpty() && stackA.isEmpty()){
return null;
}
if (stackB.isEmpty()){
while (!stackA.isEmpty()){
stackB.add(stackA.pop());
}
}
return stackB.pop();
}
/**
* peek 操作不取出元素,只回傳佇列頭部的元素值
* @return 佇列頭部的元素值
*/
public E peek(){
//如果佇列中沒有元素則直接回傳空,也可以選擇拋出例外
if (stackB.isEmpty() && stackA.isEmpty()){
return null;
}
if (stackB.isEmpty()){
while (!stackA.isEmpty()){
stackB.add(stackA.pop());
}
}
return stackB.peek();
}
}
uj5u.com熱心網友回復:
參考 樓主 煙雨、相思醉的回復: 無論如果 StackA(最開始add元素的那個堆疊) 要往 StackB 中壓入元素,那么必須選擇一次性全部壓入。
無論什么時候從佇列中取元素,必須保證元素是從 StackB 中 pop 出的,也就是說,當 StackB 不為空的時候絕不能再次向 StackB 中壓入元素。
也就是在存入元素一直往 StackA 中存,取元素是從 StackB 中取,但要要注意的是取的時候需要保證 StackB 為空的時候要先將 StackA 中元素一次性壓如 StackB 中,在進行從 StackB 中取的操作。
public static class TwoStackQueue<E>{
private Stack<E> stackA;
private Stack<E> stackB;
public TwoStackQueue() {
stackA = new Stack<>();
stackB = new Stack<>();
}
/**
* 添加元素邏輯
* @param e 要添加的元素
* @return 這里只是遵循 Queue 的習慣,這里簡單處理回傳 true 即可
*/
public boolean add(E e){
stackA.push(e);
return true;
}
/**
* 去除元素的時候需要判斷兩個地方,StackA & StackB 是否都為空
* StackB 為空的時候講StackA中的元素全部依次壓入 StackB
* @return 回傳佇列中的元素 如果佇列為慷訓傳 null
*/
public E poll(){
//如果佇列中沒有元素則直接回傳空,也可以選擇拋出例外
if (stackB.isEmpty() && stackA.isEmpty()){
return null;
}
if (stackB.isEmpty()){
while (!stackA.isEmpty()){
stackB.add(stackA.pop());
}
}
return stackB.pop();
}
/**
* peek 操作不取出元素,只回傳佇列頭部的元素值
* @return 佇列頭部的元素值
*/
public E peek(){
//如果佇列中沒有元素則直接回傳空,也可以選擇拋出例外
if (stackB.isEmpty() && stackA.isEmpty()){
return null;
}
if (stackB.isEmpty()){
while (!stackA.isEmpty()){
stackB.add(stackA.pop());
}
}
return stackB.peek();
}
}
厲害!!!!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/183040.html
標籤:Java相關
上一篇:FastReport報表:Footer1里Memo1控制元件自適應行高的問題?
下一篇:Python flask框架對資料庫的增刪改如何判斷是否成功