1.兩個棧實現一個隊列
- 思路:壓入元素直接入stack1,刪除元素先判斷stack2中是否爲空,若是不爲空直接彈出;爲空則將stack1中的元素取出壓入 stack2中再彈出。
- 代碼:
import java.util.Stack;
public class TwoStackToQueue {
private Stack stack1 = new Stack();
private Stack stack2 = new Stack();
public void add(Integer n){
stack1.push(n);
}
public Integer poll(){
if(stack1.isEmpty()&&stack2.isEmpty()){
return null;
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return (Integer)stack2.pop();
}
public boolean isEmpty(){
if(stack1.isEmpty()&&stack2.isEmpty()){
return true;
}else{
return false;
}
}
}
複製代碼
2.兩個隊列實現一個棧
- 思路:要用隊列(先進先出)實現棧(先進後出),則是要獲取deque1隊尾的元素,因此能夠把前n-1個元素壓入空隊列deque2中,彈出deque1剩餘的一個隊尾元素。
- 代碼:
import java.util.ArrayDeque;
import java.util.Deque;
public class TwoQueueToStack {
private Deque<Integer> deque1;
private Deque<Integer> deque2;
public TwoQueueToStack(){
deque1 = new ArrayDeque<>();
deque2 = new ArrayDeque<>();
}
public void push(Integer n){
if(deque2.isEmpty()){
deque1.offer(n);
}else {
deque2.offer(n);
}
}
public Integer pop(){
if(deque1.isEmpty()&&deque2.isEmpty()){
return null;
}
if(deque1.isEmpty()&&!deque2.isEmpty()){
while (deque2.size()>0){
deque1.add(deque2.poll());
}
}
while (deque1.size()>1){
deque2.add(deque1.poll());
}
return deque1.poll();
}
public boolean isEmpty(){
if(deque1.isEmpty()&&deque2.isEmpty()){
return true;
}else{
return false;
}
}
}
複製代碼