用栈实现队列
基本思想
- 实现两个栈:push栈、pop栈
- push栈:元素入栈
- pop栈:元素出栈
- 入栈:元素入栈时进push栈
- 出栈:元素出栈时,判断pop栈是否为空
- 如果pop栈不为空,弹出pop栈顶元素
- 如果pop栈为空,则判断push栈是否为空
- 如果push栈为空,则没有数据可以出栈
- 如果push栈不为空,将push栈所有元素弹出压入到pop栈,pop栈顶弹出
代码
import java.util.Stack;
public class StackQueue {
public static class MyQueue{
public Stack<Integer> pushStack;
public Stack<Integer> popStack;
public MyQueue(){
pushStack = new Stack<Integer>();
popStack = new Stack<Integer>();
}
public void push(int value){
pushStack.push(value);
}
public int pop(){
if (!popStack.isEmpty()){
return popStack.pop();
} else if (!pushStack.isEmpty()){
while (!pushStack.isEmpty()){
popStack.push(pushStack.pop());
}
return popStack.pop();
} else {
System.out.println("队列为空!");
return -1;
}
}
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
myQueue.push(1);
myQueue.push(2);
System.out.println(myQueue.pop());
System.out.println(myQueue.pop());
System.out.println(myQueue.pop());
myQueue.push(30);
myQueue.push(10);
System.out.println(myQueue.pop());
}
}
用队列实现栈
基本思想
- 用两个队列实现栈:data队列,help队列
- 入栈时,放入data队列
- 出栈时,将data队列中除去队尾元素,全部放到help队列中,data队列的队尾元素出队
- 将help队列与data队列交换,即原本的help队列转为新的data队列,原本的data队列转为新的help队列
代码
import java.util.ArrayDeque;
import java.util.Queue;
public class QueueStack {
public static class MyStack{
public static Queue<Integer> dataQueue;
public static Queue<Integer> helpQueue;
public MyStack(){
dataQueue = new ArrayDeque<>();
helpQueue = new ArrayDeque<>();
}
public void push(int value){
dataQueue.add(value);
}
public int pop(){
if (dataQueue == null){
System.out.println("栈为空");
return -1;
} else {
while (dataQueue.size() != 1){
helpQueue.add(dataQueue.remove());
}
swap(dataQueue,helpQueue);
return helpQueue.remove();
}
}
private void swap(Queue<Integer> dataQueue, Queue<Integer> helpQueue) {
Queue<Integer> myQueue = new ArrayDeque<>();
while (helpQueue.size()!=0){
myQueue.add(helpQueue.remove());
}
while (dataQueue.size()!=0){
helpQueue.add(dataQueue.remove());
}
while (myQueue.size() != 0){
dataQueue.add(myQueue.remove());
}
}
}
public static void main(String[] args) {
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(6);
System.out.println(myStack.pop());
myStack.push(3);
System.out.println(myStack.pop());
myStack.push(4);
System.out.println(myStack.pop());
}
}