栈的压入弹出序列

#include <iostream>
#include <stack>

using namespace std;

bool isPopOrder(const int* pPush, const int* pPop, int nlength) {

    if (pPush == nullptr || pPop == nullptr || nlength < 0)
        return false;
    const int* pNextPop = pPop;
    const int* pNextPush = pPush;

    stack<int> stackData;
    while (pNextPop - pPop < nlength) {
        if (!stackData.empty() && stackData.top() == *pNextPop) {
            stackData.pop();
            ++pNextPop;
            continue;
        }
        if (pNextPush - pPush >= nlength)
            break;
        if (*pNextPush == *pNextPop) {
            ++pNextPop;
            ++pNextPush;
            continue;
        }

        stackData.push(*pNextPush);
        ++pNextPush;
    }
    if (stackData.empty())
        return true;
    return false;

}

int main() {
    int pPush[5] = { 1, 2, 3, 4, 5 };
    int pPop[5] = { 4, 3, 5, 1, 2 };
    if (isPopOrder(pPush, pPop, 5)) {
        cout << 1 << endl;
    }
    else {
        cout << 0 << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ruihuank/article/details/80037779