CheckSequence.cpp
#include<iostream>
#include <assert.h>
using namespace std;
#include <stack>
bool Checksequence(int *stackIn, int *stackOut,int lenIn,int lenOut){
assert(stackIn && stackOut);
if (lenIn != lenOut) //两个序列长度不相等,不合法
return false;
stack<int> s;
for (int i = 0; i < lenIn; i++){
int j = 0;
s.push(stackIn[i]);
while (s.size() > 0 && s.top() == stackOut[j]){ //入栈序列栈顶元素与当前出栈序列元素不相等,不合法
s.pop();
j++;
}
}
return (s.size()>0) ?false:true; //当所有出栈序列元素都匹配完之后,栈不为空,不合法
}
int main(){
int stackIn[] = { 1, 2, 3, 4, 5 }; //入栈序列
int stackOut[] = { 5, 4, 2, 3, 1 }; //出栈序列
int len_in = sizeof(stackIn) / sizeof(stackIn[0]); //入栈序列长度
int len_out = sizeof(stackOut) / sizeof(stackOut[0]); //出栈序列长度
bool ret = Checksequence(stackIn, stackOut,len_in,len_out);
if (ret)
cout << "出栈顺序合法" << endl;
else
cout << "出栈顺序不合法" << endl;
return 0;
}本文出自 “moLova” 博客,请务必保留此出处http://molova.blog.51cto.com/10594266/1711367
原文地址:http://molova.blog.51cto.com/10594266/1711367