您的位置:首页 > 理论基础 > 数据结构算法

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

2012-12-13 22:58 225 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐