当前位置: 代码迷 >> 综合 >> 剑指offer-Java实现:题目5、利用两个栈实现队列
  详细解决方案

剑指offer-Java实现:题目5、利用两个栈实现队列

热度:83   发布时间:2023-09-22 11:33:01.0

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

 

思路:栈的特点:先进后出 。 队列特点:先进先出。自己画了画图,看的比较秦楚,大概是每次进队列操作都进stack1栈,出队列时必须先把stack1弹栈到stack2中,这样刚好就是倒过来的顺序了。

stack1 :    1      >      2  1 >     3  2  1 > .

stack2 :    3      >      2   3  >     1  2   3 

所以出队时就弹出最后面进入的元素。

最重要的是,每次弹完 为了保持队列顺序必须要 再 把stack2完全弹栈到stack1中

stack 1  :    2   >   3   2 .

stack 2  :    null;

 

代码:

import java.util.Stack;public class Solution {Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();int k=0;public void push(int node) {stack1.push(node);k++;}public int pop() {if(stack1.isEmpty()){return 0;}while(!stack1.isEmpty()){stack2.push(stack1.pop());}int x = stack2.pop();while(!stack2.isEmpty()){stack1.push(stack2.pop());}return x;}
}