232.Implement Queue using Stacks(Stack-Easy)

转载请注明作者和出处:http://blog.csdn.net/c406495762

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 top, peek/pop from top, size, 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).

题目: 用Stacks实现Queue。

思路: Queue是先进先出FIFO,Stack是先进后出FILO。使用Stack模拟实现Queue的功能,可以使用两个Stack,一个进行入Stack操作,一个进行出Stack操作。这两个Stack中的元素位置是颠倒的。比如,一个元素在第一个Stack位于Stack头,那么这个元素在另一个Stack则位于Stack尾。

Language : cpp

class MyQueue {
public:

stack<int> input, output;
/** Push element x to the back of queue. */
void push(int x) {
    input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
    int a = peek();
    output.pop();
    return a;
}

/** Get the front element. */
int peek() {
    if(output.empty()){
        while(input.size()){
            output.push(input.top());
            input.pop();
        }
    }
    return output.top();
}

/** Returns whether the queue is empty. */
bool empty() {
    return input.empty() && output.empty();
}

};

/**
* 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();
*/

你可能感兴趣的:(LeetCode,Queue,stack)