第三章 栈和队列

算法设计题:
(5)假设以I和O分别表示入栈和出栈操作。栈的初态和终态均为空,入栈和出栈的操作序
列可表示为仅由I和O组成的序列,称可以操作的序列为合法序列,否则称为非法序列。
在这里插入图片描述

#include <stdio.h>
#include <string.h>

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1

typedef int Status;
typedef char SElemType;
typedef struct SNode
{
    char data;
    struct SNode *next;
} SNode, *LinkStack;
//初始化
Status InitStack(LinkStack &S)
{
    S = NULL;
    return OK;
}
//判断栈空
Status StackEmpty(LinkStack S)
{
    if (!S)
        return TRUE;
    return FALSE;
}
//进栈
Status Push(LinkStack &S, SElemType e)
{
    SNode *p = new SNode;
    p->data = e;
    p->next = S;
    S = p;
    return OK;
}
//出栈
Status Pop(LinkStack &S)
{
    if (StackEmpty(S))
        return ERROR;
    SNode *p = S;
    S = S->next;
    delete p;
    return OK;
}
//判断算法
Status Judge(LinkStack &S, char str[])
{
    InitStack(S);
    int i = 0;
    while (str[i] != '\0')
    {
        if (str[i] == 'I')
            Push(S, str[i]);
        else if (str[i] == 'O')
        {
            if (!Pop(S))
                return FALSE;
        }
        i++;
    }
    if (StackEmpty(S))
        return TRUE;
    return FALSE;
}

int main(void)
{
    LinkStack S;
    char str[20];
    printf("请输入仅由IO组成的序列:");
    scanf("%s", str);
    if (Judge(S, str))
        printf("%s为合法序列\n", str);
    else
        printf("%s为非法序列\n", str);

    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值