您的位置:首页 > 其它

栈-括号匹配的检验

2012-04-24 19:07 260 查看
#include<stdio.h>
#include<malloc.h>
#define STACK_INIT_SIZE 100//初始分配量
#define STACKINCREMENT 10//存储空间分配增量
#define ERROR 0
#define OK 1
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;
typedef struct{
ElemType *top;
ElemType *base;
int stacksize;
}SqStack;
//得到栈的长度
Status GetLen(SqStack &S){
if(!S.base) return 0;
return S.top-S.base;
}
//打印栈的元素
Status PrintStack(SqStack &S){
if(!S.base) return ERROR;
ElemType *temp=S.top;
int length=GetLen(S);
printf("长度:%d\n",length);
printf("栈的元素:");
while(temp!=S.base){
printf("%c,",*--temp);
}
printf("\n");
}

//初始化栈
Status InitStack(SqStack &S){
S.base=(ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);
if(!S.base) return OVERFLOW;
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
}
Status matchkh(SqStack &S){
if(!S.base) return OVERFLOW;
char cs[]={'[','(','[',']','[',']',')',']'};
for(int i=0;i<8;i++){
ElemType *temp=S.top;
*(S.top++)=cs[i];
if(*(S.top-1)==']'&&*(S.top-2)=='['||*(S.top-1)==')'&&*(S.top-2)=='('){
*--S.top;
*--S.top;
}
printf("%c,%c\n",*(temp-1),*(S.top-1));
}
return OK;
}

int main(){
SqStack S;
InitStack(S);
PrintStack(S);
matchkh(S);
PrintStack(S);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: