程序员

判断栈的pop序列

2016-04-06  本文已影响142人  AwesomeAshe

比如一个栈的压栈顺序为1,2,3,4,5;那么3,2,1,4,5就可能是栈的pop序列;
而4,2,3,1,5就不可能,因为要先pop 4,就必须先把1,2,3,4压栈进去,那么要pop2 的话,先得pop3。

所以这个题就看你怎么去利用这个条件了。

我的思路是这样的:有一个stack和两个数组,push和pop,两个数组分别保存两个序列,stack是用来模拟pop和push的情况的。
首先我们要pop的数记为*popnode,然后我们在栈里面寻找这个值,如果找不到的话,我们看还有没有剩下的未push的数字,如果有的话,我们把它们都push进去直到找到我们要pop的数字或者已经把所有的数字都push进去了。
举个例子:
push[]={1,2,3,4,5},pop[]={4,3,2,1,5); popnode=4->push 1,2,3,4; pop 4; popnode=5->push 5; pop 5; pop 3,2,1
根据上面的思路写出的代码:
里面加入了一些输出,debug的时候用的,也可以用来理清思路:

运行结果
bool solution(int* push, int* pop, int len)
{
    if (!pop || !push || len <= 0)
        return false;
    std::stack<int> s;
    bool k = true;
    int* popnode = pop;
    int* pushnode = push;
    while (popnode - pop < len)
    {
        while (s.empty()||(s.top() != *popnode&&(pushnode<len+push)))
        {
            if(!s.empty())
                std::cout << "s.top=" << s.top() << " popnode=" << *popnode << "\n";
            s.push(*pushnode++);
            
            std::cout << "push:" << *(pushnode - 1)<<"\n";
        }
        if (s.top() == *popnode)
        {
            std::cout << "pop node :" << *popnode << std::endl;
            s.pop();
            popnode++;
        }
        else if ((pushnode - push >= len - 1))
        {
            std::cout << "to break"<<"\n";
            k = false;
            //popnode = pop + 5;
            break;
            //return false;
        }
    }
    return k;
}
int main()
{
    int push[] = { 1, 2, 3, 4, 5 };
    int pop[] = {4,5,3,2,1 };//4,5,3,2,1
    if (solution(push, pop, 5))
        std::cout << "yes!";
    else std::cout << "no!";
}
上一篇 下一篇

猜你喜欢

热点阅读