兩個棧實現佇列-兩個佇列實現棧
阿新 • • 發佈:2019-02-07
1、兩個棧實現佇列
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
/**
* stack1:使用者加入資料,之壓到stack1中
* stack2:只給使用者返回資料
*/
public void push(int node) {
stack1. push(node);
}
public int pop() {
if(stack1.empty() && stack2.empty()){
throw new RuntimeException("Queue is empty");
}
/**
* 如果stack2不為空,直接給使用者返回資料
* 如果為空,把stack1中的資料全部出棧,並全部壓入stack2中,stack2彈出資料給使用者
*/
if(stack2.empty ()){
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
2、兩個佇列實現棧
解題思路:根據棧的先入後出和佇列的先入先出的特點
1、在push的時候,把元素向非空的佇列內新增
2、在pop的時候,把不為空的佇列中的size()-1份元素poll出來,新增到另為一個為空的佇列中,再把佇列中最後的元素poll出來。兩個佇列在棧不為空的情況下始終是有一個為空,另一個不為空的。push新增元素到非空的佇列中,pop把非空佇列的元素轉移到另一個空的佇列中,直到剩下最後一個元素,這個元素就是要出棧的元素(最後新增到佇列中的元素)。
public class Test {
public static void main(String[] args) {
push(1);
push(2);
push(3);
pop();
push(4);
pop();
pop();
pop();
}
static Queue<Object> queue1 = new LinkedList<>();
static Queue<Object> queue2 = new LinkedList<>();
/**
* 向佇列中執行入棧操作,把元素新增到非空的佇列中
* @param item
*/
public static void push(Object item){
if(!queue1.isEmpty()){
queue1.offer(item);
}else{
queue2.offer(item);
}
System.out.println("入棧元素:" + item);
}
/**
* 出棧
* @return
*/
public static void pop(){
if(!(queue1.isEmpty() && queue2.isEmpty())){
if(queue1.isEmpty()){
while (queue2.size() > 1){
queue1.offer(queue2.poll());
}
System.out.println("出棧元素:" + queue2.poll());
}else{
if(queue2.isEmpty()){
while (queue1.size() > 1){
queue2.offer(queue1.poll());
}
System.out.println("出棧元素:" + queue1.poll());
}
}
}else{
//兩個佇列都是空的,異常
throw new RuntimeException("棧為空,無法執行出棧操作");
}
}
}