判断序列的合法性

该程序实现了一个功能,检查是否能通过栈操作将1到N的递增序列转换为给定的序列。通过创建和操作ArrayStack结构体,实现了push、pop、Top等栈操作,最终判断给定序列如2,1,5,4,3是否可以转换。如果不能转换,输出impossible。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

判断能否用栈 将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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值