//隊(duì)列轉(zhuǎn)棧
import java.util.LinkedList;
import java.util.Queue;
public class Queue_To_Stack {
private static Queue<Integer> data ; //原本的數(shù)據(jù)隊(duì)列
private static Queue<Integer> help ; // 輔助隊(duì)列
public static void setStack(){ //定義一個(gè)棧
data = new LinkedList<>();
help = new LinkedList<>();
}
public static void push(int num){ //壓入棧
data.add(num);
}
public static Integer pop(){ //出棧
if(data.isEmpty()){
throw new IllegalArgumentException("棧為空!") ;
}
while(data.size() > 1){ //全部出隊(duì)列武通,直到最后一個(gè)
help.add(data.poll()) ;
}
int res = data.poll(); //得到最后一個(gè)
swpe(); // help 和 data交換
return res ;
}
public static Integer peek(){ //棧頂元素
if(data.isEmpty()){
throw new IllegalArgumentException("棧為空霹崎!") ;
}
while(data.size() > 1){
help.add(data.poll()) ;
}
int res = data.poll();
data.add(res) ;
swpe();
return res ;
}
public static void swpe(){
Queue<Integer> tmp = help;
help = data;
data = tmp;
}
public static void main(String[] args) {
setStack();
push(2);
push(44);
push(11);
push(266);
push(277);
push(200);
System.out.println(pop());
System.out.println(peek());
}
}
//棧轉(zhuǎn)隊(duì)列
import java.util.Stack;
public class Stack_To_Queue {
private static Stack<Integer> data;
private static Stack<Integer> help ;
public static void setQueue(){
data = new Stack<>();
help = new Stack<>();
}
public static void add(int num){
data.push(num) ;
}
public static Integer poll(){
if(data.isEmpty() && help.isEmpty()){
throw new RuntimeException("隊(duì)列為空!") ;
}else{
while(data.size()>0){
help.push(data.pop()) ;
}
int res = help.pop();
while(!help.isEmpty()){
data.push(help.pop()) ;
}
return res ;
}
}
public static Integer peek(){
if(data.isEmpty() && help.isEmpty()){
throw new RuntimeException("隊(duì)列為空!") ;
}else{
while(data.size()>0){
help.push(data.pop()) ;
}
int res = help.peek();
while(!help.isEmpty()){
data.push(help.pop()) ;
}
return res ;
}
}
public static void main(String[] args) {
setQueue();
add(1);
add(2);
add(3);
add(4);
add(5);
System.out.println(poll());
System.out.println(poll());
System.out.println(poll());
System.out.println(poll());
System.out.println(poll());
}
}