题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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-232:用栈实现队列一样,只不过,这道题,只需要实现增、删
class CQueue { public: stack<int> st1; stack<int> st2; CQueue() { } void appendTail(int value) { while(!st1.empty()){ st2.push(st1.top()); st1.pop(); } st1.push(value); while(!st2.empty()){ st1.push(st2.top()); st2.pop(); } } int deleteHead() { if(st1.empty()) return -1; int num=st1.top(); st1.pop(); return num; } };