判断能否用栈 将1~ N 的递增序列 转换为指定序列
提示:
输入序列:2,1,5,4,3
输出:push (1), push (2), pop (2), pop (1), push (3), push (4), push (5), pop (5), pop (4), pop (3)
输入序列5,1,2,3,4
输出:impossible
#include <iostream>
using namespace std;
typedef int Element;//大写
#define MaxStackSize 100//无;
typedef struct {
Element date[MaxStackSize];
int top;//栈顶索引
}ArrayStack;
ArrayStack* createarraystack() {
ArrayStack* stack = (ArrayStack*)malloc(sizeof(ArrayStack));
if (stack == NULL) {
cout << "createarraystack fail";
}
stack->top = -1;
return stack;
}
int pusharraystack(ArrayStack* stack, Element e) {
if (stack->top >= MaxStackSize - 1) {
cout << "pusharraystack fail,full ";
return -1;
}
stack->date[++stack->top] = e;
return 0;
}
int Top(ArrayStack* stack, int& x) {//引用
if (stack) {
x = stack->date[stack->top];
return 0;
}
return 1;//异常结束
}
int poparraystack(ArrayStack* stack, Element* e) {
if (stack->top < 0) {
cout << "poparraystack fail,empty ";
return -1;
}
*e = stack->date[stack->top--];//把里面内容取出来给上层地址
return 0;
}
void releasearraystack(ArrayStack* stack) {
if (stack) {
free(stack);
}
}
int main()
{
int n,x;
Element a[MaxStackSize] = { 0 };
Element e=0;
ArrayStack* stack = createarraystack();
cout << "请输入序列元素个数\n";
cin >> n;
cout << "请输入待判断合法性的出栈序列\n";
for (int j = 0; j < n; j++) {
cin >> a[j];
}
Element j = 0;
for (int i = 1; i <= n; i++) {
pusharraystack(stack, i);
cout << "push(" << i << "),";
while (stack) {//考虑连续pop情况
Top(stack, x);
if (a[j] == x) {//想调用栈顶元素,可data数组下标不知道怎么确定
poparraystack(stack,&e);
cout << "pop(" << e << "),";
j++;
}
else {
break;//别忘了跳出循环
}
}
}
if (stack->top >= 0) {
cout << "impossible";
}
releasearraystack(stack);
return 0;
}