剑指Offer09 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 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]
用第一个栈作为队列末尾,每次往里面push。第二个栈作为队列的头,从第二个栈取数。
如果第二个栈不空,可以直接取,因为他是倒序的。如果第二个栈空,则把第一个栈的所有数轮流压入第二个栈再取。
1 class CQueue { 2 private: 3 stack<int> t1; 4 stack<int> t2; 5 6 public: 7 CQueue(){ 8 while(!t1.empty()) 9 t1.pop(); 10 while(!t2.empty()) 11 t2.pop(); 12 } 13 14 void appendTail(const int value) { 15 t1.push(value); 16 return ; 17 } 18 19 int deleteHead() { 20 if(!t2.empty()){ 21 int ret=t2.top(); 22 t2.pop(); 23 return ret; 24 } 25 if(t1.empty()) 26 return -1; 27 int temp; 28 while(!t1.empty()){ 29 temp=t1.top(); 30 t1.pop(); 31 t2.push(temp); 32 } 33 int ret=t2.top(); 34 t2.pop(); 35 return ret; 36 } 37 }; 38 39 /** 40 * Your CQueue object will be instantiated and called as such: 41 * CQueue* obj = new CQueue(); 42 * obj->appendTail(value); 43 * int param_2 = obj->deleteHead(); 44 */
第二次写,增加了全局变量,不过题目要求了错误时返回-1,感觉也还是可以加上。
1 enum{Valid, InValid}; 2 int g_CQueue=Valid; 3 4 class CQueue { 5 private: 6 stack<int> in_s; 7 stack<int> out_s; 8 public: 9 CQueue() { 10 cout<<"CQueue object is created"<<endl; 11 } 12 13 void appendTail(int value) { 14 in_s.push(value); 15 } 16 17 int deleteHead() { 18 int ans=-1; 19 if(!out_s.empty()){ 20 ans=out_s.top(); 21 out_s.pop(); 22 } 23 else if(!in_s.empty()){ 24 while(!in_s.empty()){ 25 int temp=in_s.top(); 26 in_s.pop(); 27 out_s.push(temp); 28 } 29 ans=out_s.top(); 30 out_s.pop(); 31 } 32 else{ 33 g_CQueue=InValid; 34 } 35 return ans; 36 } 37 }; 38 39 /** 40 * Your CQueue object will be instantiated and called as such: 41 * CQueue* obj = new CQueue(); 42 * obj->appendTail(value); 43 * int param_2 = obj->deleteHead(); 44 */