双栈队列练习题

来源:互联网 发布:网络借贷信息管理办法 编辑:程序博客网 时间:2024/04/24 13:27

编写一个类,只能用两个栈结构实现队列,支持队列的基本操作(push,pop)。

给定一个操作序列ope及它的长度n,其中元素为正数代表push操作,为0代表pop操作,保证操作序列合法且一定含pop操作,请返回pop的结果序列。

测试样例:

[1,2,3,0,4,0]6

返回:[1,2]


代码:

class TwoStack {    stack<int> stackpush;    stack<int> stackpop;public:    vector<int> twoStack(vector<int> ope, int n)    {        vector<int> temp;        for(int i=0; i<n; i++)               {            if(ope[i]>0)                      {                push(ope[i]);            }            else if(0 == ope[i])                       {                temp.push_back(pop());            }        }        return temp;    }    void push(int value)       {        stackpush.push(value);    }    int pop()       {        if(stackpop.empty())                {            while(0 != stackpush.size())                       {                stackpop.push(stackpush.top());                stackpush.pop();            }        }         int temp_pop=stackpop.top();          stackpop.pop();        return temp_pop;    }};


容易出现错误的地方:

1.stack.pop()没有返回值;

2.vector向数组末尾插入数据的操作是:push_back(value)

0 0
原创粉丝点击