用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入: ["CQueue","appendTail","deleteHead","deleteHead"] [[],[3],[],[]] 输出:[null,null,3,-1] 示例 2:
输入: ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"] [[],[],[5],[2],[],[]] 输出:[null,-1,null,null,5,2]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路1:用两个栈来的话,因为栈是FILO,所以两个轮转一下就是FIFO咯?这里是我自己写的代码,但是执行很慢!
class CQueue { public: CQueue() { } stack<int>s1; stack<int>s2; void appendTail(int value) { s1.push(value); } int deleteHead() { if(s1.empty()) return -1; while(!s1.empty()) { s2.push(s1.top()); s1.pop(); } int value = s2.top(); s2.pop(); while(!s2.empty()) { s1.push(s2.top()); s2.pop(); } return value; } }; /** * Your CQueue object will be instantiated and called as such: * CQueue* obj = new CQueue(); * obj->appendTail(value); * int param_2 = obj->deleteHead(); */思路2:看代码可以发现大佬没有将第二个栈又拷贝回去,因为只要temp_stack非空,那么存的一定就是队列的头元素以及第二个元素等等。实际上temp_stack作了一个缓冲。
class MyQueue { public: /** Initialize your data structure here. */ MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { data_stack.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { if(temp_stack.empty()) { while(!data_stack.empty()) { temp_stack.push(data_stack.top()); data_stack.pop(); } } if(temp_stack.empty()) return -1; int value = temp_stack.top(); temp_stack.pop(); return value; } /** Get the front element. */ int peek() { if(temp_stack.empty()) { while(!data_stack.empty()) { temp_stack.push(data_stack.top()); data_stack.pop(); } } if(temp_stack.empty()) return -1; return temp_stack.top(); } /** Returns whether the queue is empty. */ bool empty() { return data_stack.empty() && temp_stack.empty(); } private: stack<int> data_stack; stack<int> temp_stack; }; /** * Your MyQueue object will be instantiated and called as such: * MyQueue* obj = new MyQueue(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */
