逻辑上其实还是挺简单的无非就是两个栈或队列相互倒数据。
/**
* 〈一句话功能简述〉<br>
* 〈用两个队列实现栈〉
*
* @author guang
* @create 2019/7/7
* @since 1.0.0
*/
public class ArrayandStack {
public static class TwoQueuesStack {//这里的栈的操作方法如push,pop由队列来实现
private Queue<Integer> queue;
private Queue<Integer> help;//作为以栈顺序出队的队列
public void TwoQueueStack() {
queue = new LinkedList<integer>();//实现了LIST的接口
help = new LinkedList<integer>();
}
public void push(int data) {
queue.add(data);
}
public int pop() {
if (queue.isEmpty()) {
throw new RuntimeException("the stack is empty");
}
while (queue.size() != 1) {//queue.size返回元素的数量
help.add(queue.poll());
}
int res = queue.poll();//将最后一个出队的数返回
swap();//交换help与queue的队列里的元素
return res;//此数便是以栈的顺序来出队的
}
public int peek() {
if (queue.isEmpty()) {
throw new RuntimeException("the stack is empty");
}
while (queue.size() != 1) {//queue.size返回元素的数量
help.add(queue.poll());//poll方法是从队列中删除第一个元素
}
int res = queue.poll();//将最后一个出队的数返回
help.add(res);
swap();
return res;
}
private void swap() {
Queue<Integer> temp = help;
help = queue;
queue = temp;
}
}
public static class TwoStatckQueue
{
private Stack<integer> stackpush;
private Stack<integer> stackpop;//使用栈实现队列的操作方法
public void TwoStackQueue(){
stackpush=new Stack<integer>();
stackpop=new Stack<integer>();
}
public void push(int data){
stackpush.push(data);
}
public int poll(){
if(stackpush.isEmpty()&&stackpop.isEmpty()){
throw new RunTimeException("the queue is empty");
}else if(stackpop.isEmpty()){
while (!stackpush.isEmpty()){//其实是两条倒数据的原则,pop 栈没数据,还有就是一次性倒完push栈
stackpop.push(stackpop.pop());//弹出的压入pop栈,则pop栈的顺序就是队列的顺序
}
}
return stackpop.pop();
}
public int peek(){
if(stackpush.isEmpty()&&stackpop.isEmpty()){
throw new RunTimeException("the queue is empty");
}else if(stackpop.isEmpty()){
while (!stackpush.isEmpty()){//其实是两条倒数据的原则,pop 栈没数据,还有就是一次性倒完push栈
stackpop.push(stackpop.pop());//弹出的压入pop栈,则pop栈的顺序就是队列的顺序
}
}
return stackpop.peek();
}
}
}