题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解析:
这不巧了吗。刚打卡完成Stack就来了这题哈哈
-
简而言之:
-
Stack,栈,是一种
先进后出(FILO)
的数据结构- 举例:子弹弹夹,压栈;或者是把东西放入箱子一样,首先是取出最后放入的物品。
-
Queue,队列,是一种
先进先出(FIFO)
的数据结构- 举例:排队,先到先得;或者像是进出隧道,依次进出。
-
-
Java中
-
Stack属于一个类,可以直接实例调用
-
而Queue 属于接口,需要验证其方法还得用它的实现类,在实现类中,我们见到了一个熟面孔
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
因此,我们可以用
Linkedlist
验证public void testQueue(){ Queue<String> queue = new LinkedList<String>(); //添加元素 queue.offer("a"); queue.offer("b"); queue.offer("c"); queue.offer("d"); queue.offer("e"); System.out.println("queue:"+queue); System.out.println("poll-->"+queue.poll()); //返回第一个元素,并在队列中删除 System.out.println("queue:"+queue); System.out.println("element-->"+queue.element()); //返回第一个元素 System.out.println("queue:"+queue); System.out.println("peek-->"+queue.peek()); //返回第一个元素 System.out.println("queue:"+queue); }
queue:[a, b, c, d, e] poll-->a queue:[b, c, d, e] element-->b queue:[b, c, d, e] peek-->b queue:[b, c, d, e]
-
-
回到题目:
假如往模拟的队列中插入[a,b,c]时,出来的顺序也必须为[a,b,c]
-
入队(模拟):假设插入stack1中
stack1:【a,b,c stack2:【
-
出队(模拟):
-
需先将stack1的数据弹至stack2然后pop即可
-
弹至stack2:
stack1:【 stack2:【c,b,a
-
pop stack2的元素
stack1:【 stack2:【c,b -->a已出栈
-
-
-
继续弹出:
-
直接弹出stack2的栈顶元素即可
stack2:【c -->b已出栈
-
-
若要继续入队出队,则直接往stack1 插入,弹至stack2再弹出即可
-
模拟如下
害,今天没带ipad画图,用记事本模拟模拟了哈哈
QueueByTwoStack ------------------------------------ ->offer _____________】【_____________ -->poll stack1 stack2 ------------------------------------
-
-
解答:
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
//插入数据至stack1
public void push(int node) {
stack1.push(node);
}
//弹至stack2中pop数据
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}