題目敘述: 這題要求透過兩個 Stack 來實現一個Queue具有的基本操作,像是 push, peek, pop 以及 empty
題目也有提醒只可以使用標準 Stack 操作來實現 You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
classMyQueue { public: MyQueue() {} stack<int> sk1; stack<int> sk2; int size_Sk1=0; int size_Sk2=0;
voidpush(int x){ sk1.push(x); size_Sk1++; } intpop(){ if(sk1.empty()){ return-1; } int result; for(int i = 0; i < size_Sk1; i++){ // if it is the last element if(i==size_Sk1-1){ result = sk1.top(); sk1.pop(); } else{ sk2.push(sk1.top()); sk1.pop(); size_Sk2++; } }
//copy sk2 to sk1 for(int i = 0; i < size_Sk2; i++){ sk1.push(sk2.top()); sk2.pop(); } size_Sk2=0; size_Sk1--; return result; } // queue.front(), This is equal to the bottom of the stack intpeek(){ if(sk1.empty()){ return-1; } int result; for(int i = 0; i < size_Sk1; i++){ // if it is the last element if(i==size_Sk1-1){ result = sk1.top(); } else{ sk2.push(sk1.top()); sk1.pop(); size_Sk2++; } } //copy sk2 to sk1 for(int i = 0; i < size_Sk2; i++){ sk1.push(sk2.top()); sk2.pop(); } size_Sk2=0; return result; } boolempty(){ if(sk1.empty()) returntrue; elsereturnfalse; } };
/** * 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(); */
說明
1 2 3 4
stack<int> sk1; stack<int> sk2; int size_Sk1=0; int size_Sk2=0;