//头文件 #include <stdio.h> #include <malloc.h> #define MaxSize 100 typedef char ElemType; typedef struct { ElemType data[MaxSize]; int top; /*栈指针*/ } SqStack; /*顺序栈类型定义*/ void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } void ClearStack(SqStack *&s) { free(s); } int StackLength(SqStack *s) { return(s->top+1); } int StackEmpty(SqStack *s) { return(s->top==-1); } int Push(SqStack *&s,ElemType e) { if (s->top==MaxSize-1) /*栈满的情况,即栈上溢出*/ return 0; s->top++; s->data[s->top]=e; return 1; } int Pop(SqStack *&s,ElemType &e) { if (s->top==-1) /*栈为空的情况,即栈下溢出*/ return 0; e=s->data[s->top]; s->top--; return 1; } int GetTop(SqStack *s,ElemType &e) { if (s->top==-1) /*栈为空的情况,即栈下溢出*/ return 0; e=s->data[s->top]; return 1; } void DispStack(SqStack *s) { int i; for (i=s->top;i>=0;i--) printf("%c ",s->data[i]); printf("\n"); } //实现函数 #include<iostream> #include "heshan1.h" using namespace std; int judge(char a[]) { int i; ElemType x; SqStack *s; InitStack(s); for(i=0;a[i]!='\0';i++) { if(a[i]=='I') Push(s,a[i]); else if(a[i]=='O') { if(s->top==-1) //遇到"o"出栈操作 先判断栈是否为空,若为空说明不合法;否则继续 { return 0; } else Pop(s,x); } } return(s->top==-1); } void main() { char a[20];int i; for(i=0;i<20;i++) { a[i]='\0'; } cout<<"请输入操作序列(I、O序列)"<<endl; cin>>a; int m=judge(a); if(m==0) cout<<"你输入的操作序列是不合法的"<<endl; else cout<<"你输入的操作序列是合法"<<endl; }