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;
}