Problem A: 判断操作是否合法(栈和队列)
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 67 Solved: 22
Description
假设以I和O分别表示进栈和出栈操作,栈的初态和终态均为空,进栈和出栈的操作序列可表示为仅由I和O组成的序列。
顺序栈的定义为
typedef struct
{
ElemType data[SizeMax];
int top;
}SqStack;
编写一个算法,判断栈中的序列是否合法!若合法则返回1,否则返回0.
需编写的算法为:int judge(SqStack *s);
Input
输入为一个字符串,表示进栈出栈的操作序列,该序列存储在栈中。
Output
若操作序列合法则输出“Yes”,否则输出"No"。
Sample Input
IOIIOIOO
Sample Output
Yes
HINT
1、只需提交你所编写的算法
2、栈的初态和终态均为空
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SizeMax 105
typedef char ElemType;
typedef struct
{ElemType data[SizeMax];int top;
}SqStack;
void InitStack(SqStack *&s)
{s=(SqStack*)malloc(sizeof(SqStack));s->top=-1;
}
bool Push(SqStack *&s,ElemType c)
{if(s->top==SizeMax-1)return false;s->top++;s->data[s->top]=c;return true;
}
int judge(SqStack *s)
{int i=-1;if(s->top==-1)return 1;while(s->top>=-1){if(s->data[s->top]=='I')i++;if(s->data[s->top]=='O')i--;if(i>-1)return 0;s->top--;}if(i!=-1)return 0;else return 1;
}
void DestroyStack(SqStack *&s)
{free(s);
}
int main()
{SqStack *s=NULL;InitStack(s);char c[SizeMax];gets(c);for(int i=0;i<(int)strlen(c);i++)Push(s,c[i]);if(judge(s))printf("Yes\n");else printf("No\n");DestroyStack(s);return 0;
}