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

本文详细介绍了使用C++实现栈数据结构的方法,包括其空间复杂度和时间复杂度分析,并通过具体示例展示了如何利用栈解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

 

转载于:https://www.cnblogs.com/kedebug/archive/2012/12/13/2817241.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值