Leetcode刷题 (二)

题目链接

两个栈实现队列: https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/comments/

题目描述:

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

示例 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]

提示:

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

题目分析:

LinkedList实现了Deque接口,所以Stack能做的事LinkedList都能做。  LinkedList<Integer> stack1;

其本身结构是个双向链表,扩容消耗少

第一个栈支持插入操作,第二个栈支持删除操作。

 1 class CQueue {
 2     private Stack stack1;
 3     private Stack stack2;
 4     
 5     public CQueue() {
 6         stack1 = new Stack<Integer>();
 7         stack2 = new Stack<Integer>();
 8     }   
 9     public void appendTail(int value) {
10         stack1.push(value);
11     }    
12     public int deleteHead() {
13         if(stack2.isEmpty()){
14             while(!stack1.isEmpty()){
15                 stack2.push(stack1.pop());
16             }
17         }
18         if(stack2.isEmpty()){
19             return -1;
20         }else{
21             return (int)stack2.pop();
22         }
23     }
24 }
25 
26 /**
27  * Your CQueue object will be instantiated and called as such:
28  * CQueue obj = new CQueue();
29  * obj.appendTail(value);
30  * int param_2 = obj.deleteHead();
31  */
原文地址:https://www.cnblogs.com/hanhao970620/p/14334439.html