m0_63879042 2022-10-13 17:14 采纳率: 0%
浏览 8

使用c语言建立栈出现一些问题

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 255
typedef struct {
char *top;
char *base;
int stacksize;

}SqStack;
int InitStack(SqStack S){
S->base=(char
)malloc(MAXSIZE*sizeof(char));
if(!S->base){
return 0;
}else{
S->stacksize=MAXSIZE;
return 1;
}
}

int Puch(SqStack *S, char e){
if(S->top-S->base==S->stacksize){
return 0;
}else{
*S->top=e;
S->top++;
return 1;
}
}
int Pop(SqStack *S, char x){
if(S->top==S->base){
return 0;
}else{
S->top--;
x=*S->top;
return 1;
}
}

char GetTop(SqStack *S){
if(S->top!=S->base){
return *(S->top-1);
}else{
return 0;
}
}

int StackEmpty(SqStack *S){
if(S->top==S->base){
return 1;
}else{
return 0;
}
}

int Matching(){
SqStack S;
InitStack(&S);
int flag=1;
char ch,x;
scanf("%c",&ch);
while(ch!='@'){
switch(ch){

        case'(':
            Puch(&S,ch);
            flag=0;
            break;
        case')':
            if(!StackEmpty(&S)&&GetTop(&S)=='('){
                Pop(&S,x);
                flag=1;
            }else{
                flag=0;
            
            }
            break;
    
    }
    scanf("%c",&ch);
    
}
if(!StackEmpty(&S)&&flag){
    return 1;
}else{
    return 0;
}

}

int main(){
int h;
h=Matching();
if(h==1){
printf("YES");

}else{
    printf("NO");
}

}

  • 写回答

2条回答 默认 最新

  • 快乐鹦鹉 2022-10-13 17:26
    关注

    InitStack函数中,你没有将top指向base

    int InitStack(SqStack S){
    S->base=(char)malloc(MAXSIZE*sizeof(char));
    if(!S->base){
    return 0;
    }else{
    S->stacksize=MAXSIZE;
    S->top = S->base;
    return 1;
    }
    }
    
    
    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 10月13日