题目:输入两个整数序列,第一个表示栈的压入顺序,青判断第二个序列是否为该栈的弹出序列。
代码示例:
#include<iostream>
#include<assert.h>
using namespace std;
#define MaxSize 100
class MyClass
{
int data[MaxSize];
int length;
public:
MyClass()
{
length = -1;
}
~MyClass()
{
}
bool empty(void);
bool push(int n);
bool pop(void);
int gettop(void);
bool IsPopSerial(int pushArr[],int popArr[], int n);
};
bool MyClass::empty(void)
{
return (length == -1);
}
bool MyClass::push(int n)
{
length++;
if (length < MaxSize)
{
data[length] = n;
return true;
}
else
return false;
}
bool MyClass::pop(void)
{
if (length >= 0)
{
length--;
return true;
}
else
{
return false;
}
}
int MyClass::gettop(void)
{
assert(length >= 0);
return data[length];
}
bool MyClass::IsPopSerial(int pushArr[], int popArr[], int n)
{
if (pushArr == NULL || popArr==NULL||n <= 0)
return false;
for (int j = 0,i=0;j<=n&&i<=n;)
{
if (empty() || gettop()!=popArr[j])
{
push(pushArr[i]);
i++;
}
int temp = gettop();
if (temp == popArr[j])
{
pop();
j++;
}
}
if (empty())
return true;
else
return false;
}
int main()
{
MyClass mystack;
const int n = 5;
int pushArr[n] = { 5,3,4,2,7};
int popArr[n] = { 4,5,3,2,7};
bool flag = mystack.IsPopSerial(pushArr,popArr, n);
if (flag)
{
for (int i = 0; i < n; i++)
cout << popArr[i] << " ";
cout << "是";
for (int i = 0; i < n; i++)
cout << pushArr[i] << " ";
cout<<"的一个出栈序列!" << endl;
}
else
{
for (int i = 0; i < n; i++)
cout << popArr[i] << " ";
cout << "不是";
for (int i = 0; i < n; i++)
cout << pushArr[i] << " ";
cout << "的一个出栈序列!" << endl;
}
}