用两个栈实现队列
用两个栈实现队列
题目链接
题目描述
描述
用两个栈来实现一个队列,使用n个元素来完成 n 次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
数据范围: n≤1000
要求:存储n个元素的空间复杂度为 O(n) ,插入与删除的时间复杂度都是 O(1)
示例
输入:
["PSH1","PSH2","POP","POP"]
返回值:
1,2
说明:
"PSH1":代表将1插入队列尾部
"PSH2":代表将2插入队列尾部
"POP“:代表删除一个元素,先进先出=>返回1
"POP“:代表删除一个元素,先进先出=>返回2示例2
输入:
["PSH2","POP","PSH1","POP"]
返回值:
2,1
解题思路
借助栈的先进后出规则模拟实现队列的先进先出
1、当插入时,直接插入 stack1
2、当弹出时,当 stack2 不为空,弹出 stack2 栈顶元素,如果 stack2 为空,将 stack1 中的全部数逐个出栈入栈 stack2,再弹出 stack2 栈顶元素
代码
package com.huang.datastructure;
import java.util.Stack;
/**
* @Author hxc
* @Date 2022/1/6
*/
public class DoubleStackToQueue {
/**
* 用两个栈来实现队列
*/
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() throws Exception {
//第二个栈要是空的
if(stack2.isEmpty()) {
while (!stack1.isEmpty()){
//把第一个栈中的数字取出来放进第二个栈中,这样数就相反了
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()) {
throw new Exception("queue is Empty");
}
//输出栈
return stack2.pop();
}
public static void main(String[] args) throws Exception {
DoubleStackToQueue queue = new DoubleStackToQueue();
queue.push(1);
System.out.println(queue.pop());
queue.push(2);
System.out.println(queue.pop());
}
}