用两个栈实现队列

时间:2021-08-08
本文章向大家介绍用两个栈实现队列,主要包括用两个栈实现队列使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

提示:

  • 1 <= values <= 10000
  • 最多会对 appendTail、deleteHead 进行 10000 次调用


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思想:

俩栈区别使用,一栈用于接收入队的数据,二栈用于装载从一栈倒过来的数据以备出队。

这样使用俩栈主要是通过执行两次栈的先进后出,从而实现队列的先进先出。

 1 /**
 2  * @author 不乏理想的三师弟
 3  *用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,
 4  *分别完成在队列尾部插入整数和在队列头部删除整数的功能
 5  */
 6 public class CQueue {
 7     private int[] stack1 = new int[10000];
 8     private int index1 = -1;
 9     
10     private int[] stack2 = new int[10000];
11     private int index2 = -1;
12     
13     public CQueue() {
14         
15     }
16     
17     public void appendTail(int value) {
18         stack1[++index1] = value;
19     }
20     
21     //若队列中没有元素,deleteHead 操作返回 -1 
22     public int deleteHead() {
23         // 如果二栈非空,直接二栈弹出一元素
24         if(index2 != -1) {
25             return stack2[index2--];
26         }
27         // 二栈为空时,如果一栈为空则代表当前队列为空
28         if(index1 == -1) {
29             return -1;
30         }
31         // 二栈为空时,一栈非空,则将一栈元素倒至二栈,继而二栈弹出元素
32         while(index1 != -1) {
33             stack2[++index2] = stack1[index1--];
34         }
35         return stack2[index2--];
36     }
37 }

原文地址:https://www.cnblogs.com/Idealbean/p/15115444.html