数据结构练习(19)栈的push、pop序列

http://zhedahht.blog.163.com/blog/static/25411174200732102055385/

很多细节操作在里面,还是比较经典的,需要反复磨练。空间复杂度O(n),时间复杂度O(n).

#include <iostream>
#include <stack>
using namespace std;

bool is_pop_order(const int *push, const int *pop, int len)
{
    bool flag = false;

    if (push && pop && len > 0)
    {
        const int *nextpush = push;
        const int *nextpop = pop;

        std::stack<int> stdata;

        while (nextpop - pop < len)
        {
            while (stdata.empty() || stdata.top() != *nextpop)
            {
                if (!nextpush)
                    break;

                stdata.push(*nextpush);

                if (nextpush - push < len - 1)
                    ++nextpush;
                else
                    nextpush = nullptr;
            }
            if (stdata.top() != *nextpop)
                break;

            stdata.pop();
            ++nextpop;
        }
        if (stdata.empty() && nextpop - pop == len)
            flag = true;
    }
    return flag;
}

int main()
{
    int a[10] = {1, 2, 3, 4, 5};
    int b[10] = {4, 5, 3, 2, 1};
    bool flag = is_pop_order(a, b, 5);
    if (flag)
        cout << "true" << endl;
    else
        cout << "false" << endl;
    return 0;
}

 

posted @ 2012-12-13 22:58  kedebug  阅读(1496)  评论(0编辑  收藏  举报