[225]Implement Stack using Queues

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

【题目描述】

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();    }};

update:

用两个queue来实现了栈,原理基本相同,不过在实现的时候要注意判断是哪个queue为空,对另一个queue操作:

class Stack {public:    queue<int>q1,q2;    // Push element x onto stack.    void push(int x) {        if(q2.size()>0) q2.push(x);        else q1.push(x);    }    // Removes the element on top of the stack.    void pop() {        int data;        if(q1.size()<=0){            while(q2.size()>1){                data=q2.front();                q2.pop();                q1.push(data);            }            q2.pop();        }        else if(q2.size()<=0){            while(q1.size()>1){                data=q1.front();                q1.pop();                q2.push(data);            }            q1.pop();        }    }    // Get the top element.    int top() {         int data;        if(q1.size()<=0){            return q2.back();        }        if(q2.size()<=0){            return q1.back();        }    }    // Return whether the stack is empty.    bool empty() {        if(q1.size()<=0&&q2.size()<=0) return true;        else return false;    }};


0 0
原创粉丝点击