#define MAXSIZE 100
typedef struct
{
char data[MAXSIZE];
int top;
}Stack;
//顺序栈的初始化
void StackInit(Stack* ps)
{
ps->top = -1;
}
//判空
int Empty(Stack* ps)
{
if (ps->top == -1)
{
return 1;
}
return 0;
}
//入栈
int push(Stack* ps, char ch)
{
if (ps->top == MAXSIZE -1)
{
printf("顺序栈空间满,无法入栈\n");
return 0;
}
ps->top++;
ps->data[ps->top] = ch;
return 1;
}
//出栈
int pop(Stack* ps, char* ch)
{
if (ps->top == -1)
{
printf("顺序栈为空,无输出内容\n");
return 0;
}
*ch = ps->data[ps->top];
ps->top--;
return 1;
}
int islegal(char arr[], int n)
{
Stack ps;
StackInit(&ps);
for (int i = 0; i < n; i++)
{
char c = arr[i];
if (c == 'I')
{
push(&ps, c);
}
else if (c == 'O')
{
if (Empty(&ps))
{
return 0;
}
else
{
char top;
pop(&ps, &top);
}
}
}
if (Empty(&ps))
{
return 1;
}
else {
return 0;
}
}
int main()
{
//1为真,0为空
char arr1[] = "IOOIOIIO";
int ret = islegal(arr1, 8);
printf("%s 字符串是 %d\n",arr1,ret);
char arr2[] = "IOIIOIOO";
int ret2 = islegal(arr2, 8);
printf("%s 字符串是 %d\n", arr2, ret2);
char arr3[] = "IIIOIOIO";
int ret3 = islegal(arr3, 8);
printf("%s 字符串是 %d\n", arr3, ret3);
char arr4[] = "IIIOOIOO";
int ret4 = islegal(arr4, 8);
printf("%s 字符串是 %d\n", arr4, ret4);
return 0;
}
假设以I和O分别表示入栈和出栈操作,栈的初态和终态均为空,入栈和出栈的操作序列可表示为仅由I和O组成的序列,称可以操作的序列为合法序列,否则称为非法序列
最新推荐文章于 2024-08-30 15:57:36 发布