import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
* 如何仅用队列结构实现栈结构?
* 如何仅用栈结构实现队列结构?
* @author Administrator
*
*/
public class Code03_QueueAndStackConvert {
// 仅用队列结构实现栈结构
public static class TwoQueueStack {
private Queue<Integer> data;
private Queue<Integer> help;
public TwoQueueStack(){
this.data = new LinkedList<Integer>();
this.help = new LinkedList<Integer>();
}
public void push(Integer num){
this.data.add(num);
}
public Integer pop(){
if(this.data.isEmpty()){
throw new RuntimeException("The stack is empty");
}
while(data.size() > 1){
help.add(data.poll());
}
int res = data.poll();
swap();
return res;
}
public Integer peek(){
if(this.data.isEmpty()){
throw new RuntimeException("The stack is empty");
}
while(data.size() > 1){
help.add(data.poll());
}
int res = data.poll();
help.add(res);
swap();
return res;
}
public void swap(){
Queue<Integer> temp;
temp = data;
data = help;
help = temp;
}
}
// 仅用栈结构实现队列结构
public static class TwoStackQueue {
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
public TwoStackQueue() {
this.pushStack = new Stack<>();
this.popStack = new Stack<>();
}
public void push(Integer num) {
pushStack.push(num);
}
public Integer poll() {
if(this.popStack.isEmpty() && this.pushStack.isEmpty())
return null;
pour();
return popStack.pop();
}
public Integer peek() {
if(this.popStack.isEmpty() && this.pushStack.isEmpty())
return null;
pour();
return popStack.peek();
}
public void pour() {
if(!this.popStack.isEmpty())
return ;
while(!this.pushStack.isEmpty()){
popStack.push(pushStack.pop());
}
}
}
}
算法入门-队栈互换
最新推荐文章于 2023-09-18 03:56:34 发布