232 - Implement Queue using Stacks

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

實現如下:
class Queue {
public:
         stack<int> A, B;
        void push(int x) {
                A.push(x);
        }

        void pop(void) {
                while(!A.empty()) {
                        B.push(A.top());
                        A.pop();
                }
                B.pop();
                while(!B.empty()) {
                        A.push(B.top());
                        B.pop();
                }
        }

        int peek(void) {
                if( !A.empty() ) {
                        while(!A.empty()) {
                                B.push(A.top());
                                A.pop();
                        }
                        int p = B.top();
                        while(!B.empty()) {
                                A.push(B.top());
                                B.pop();
                        }
                        return p;
                }
                return 0;
        }

        bool empty(void) {
                return A.empty();
        }
};

int main() {
        Queue queue;
        queue.push(1);
        queue.push(2);
        queue.push(3);
        while(!queue.empty()) {
                cout << queue.peek();
                queue.pop();
        }
        //queue.pop();
        cout << queue.peek() << endl;
        if(queue.empty() == true)
                cout << "empty" << endl;
        else
                cout << "not empty" << endl;
        return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章