C++:检查出栈顺序的合法性

2015-11-21 00:55:08 · 作者: · 浏览: 6
CheckSequence.cpp
 
#include
#include 
using namespace std;
#include 
bool Checksequence(int *stackIn, int *stackOut,int lenIn,int lenOut){
 assert(stackIn && stackOut);
 if (lenIn != lenOut)         //两个序列长度不相等,不合法
  return false;
 stack 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; }