[225]Implement Stack using Queues

来源:互联网 发布:李连杰国际影响力 知乎 编辑:程序博客网 时间:2024/05/17 06:44

【题目描述】

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.

【思路】

queue成员函数

  • empty()判断队列空,当队列空时,返回true。
  • size()访问队列中的元素个数。
  • push()会将一个元素置入queue中。
  • front()会返回queue内的第一个元素(也就是第一个被置入的元素)。
  • back()会返回queue中最后一个元素(也就是最后被插入的元素)。
  • pop()会从queue中移除一个元素。[1] 
  • 注意:pop()虽然会移除下一个元素,但是并不返回它,front()和back()返回下一个元素但并不移除该元素。
【代码】

class Stack {public:    queue<int> s;    // Push element x onto stack.    void push(int x) {        s.push(x);    }    // Removes the element on top of the stack.    void pop() {        int n=s.size();        if(n==0) return;        for(int i=0;i<n-1;i++){            s.push(s.front());            s.pop();        }        s.pop();    }    // Get the top element.    int top() {        return s.back();    }    // Return whether the stack is empty.    bool empty() {         return s.empty();    }};


0 0
原创粉丝点击