用两个栈来实现一个队列||用两个队列实现一个栈

1.用两个栈来实现一个队列,完成队列的Push和Pop操作。

   队列中的元素为int类型。

 

实现思路:

    利用栈last in first out 的特性,使用两个栈可以实现队列的pop和push操作。

    push: 往stack1中push元素。

    pop: 先判断stack2是否为空,若为空,将stack1中的所有元素pop至stack2中,取出stack2的栈顶元素pop出去

       若不为空,直接取出stack2的栈顶元素pop出去;

class Solution
{
public:
    void push(int node) {
         stack1.push(node);
    }

    int pop() {
       if(stack2.empty())
       {
            while(!stack1.empty())
            {
                int t=stack1.top();
                stack2.push(t);
                stack1.pop();
            }
       }
        int s=stack2.top();
        stack2.pop();
        return s;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

 

2.用两个队列来实现一个,完成的Push和Pop操作。

   队列中的元素为int类型。

  思路:

         定义一个队列为存储队列(queue1),另一个为中转队列(queue2)。

   入栈时直接压入queue1中,出栈时先将除queue1最后一个元素外依次pop出队列,并压入queue2中,将留在queue1中的最后一个元素出队列即为出队元素,之后再次将queue2中的元素压回queue1中。

 void stackpush(queue<int> &q1,int m)
 {
     q1.push(m);
 }

 int stackpop(queue<int> &q1,queue<int> &q2)
 {
     int num=q1.size();
     for(int i=0;i<num-1;i++)
     {
         q2.push(q1.front());
         q1.pop();
     }
     int res=q1.front();
     q1.pop();

     for(int i=0;i<q2.size();i++)
     {
         q1.push(q2.front());
         q2.pop();
     }

     return res;
 }

 

posted @ 2019-04-17 19:41  小新猩  阅读(4153)  评论(0编辑  收藏  举报