算法设计题:
(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;
}