为什么我在c中使用stack的后缀代码的缀无法正常工作?

时间:2018-09-29 18:47:17

标签: c

今天,我试图编写一个将中缀表达式转换为后缀表达式的代码,我的代码正在运行但不能正常工作,

我上传了我的整个代码,请让我知道我的代码有什么问题,

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAXSTACK 50

typedef char StackEntyType;
typedef enum{false, true}Boolean;

typedef struct{
        int top;
        StackEntyType entry[MAXSTACK];
}stack;

创建堆栈,

void CreateStack(stack *S){
    S->top = -1;
}

检查堆栈为空,

Boolean IsStackEmpty(stack *S){
    return S->top==-1;
}

检查堆栈已满,

Boolean IsStackFull(stack *S){
    return S->top == MAXSTACK-1;
}

用于推送堆栈元素的代码,

void Push(StackEntyType item, stack *S){
    if(IsStackFull(&S)){
        printf("Stack is overflow\n");
    }else{
        S->entry[++S->top] = item;
    }
}

代码以弹出堆栈元素,

void Pop(StackEntyType *item, stack *S){
    if(IsStackEmpty(&S)){
        printf("Stack is underflow\n");
    }else{
        *item = S->entry[S->top--];
    }
}

返回顶部堆栈元素的代码,

char Peek(stack *S){
    return S->entry[S->top];
}

返回操作符优先级的代码,

int Oprecedence(char elem){
    switch(elem){
        case '-':
        case '+':
            return 0;
        case '*':
        case '/':
            return 1;
        case '^':
            return 2;
    }
}

主要代码

void main()
{
    char infix[50];
    char postfix[50];
    char c;
    char elem;

    stack S;

    int i=0;
    int k=0;
    CreateStack(&S);
    printf("Enter infix expression : ");
    scanf("%s", infix);

    while(!IsStackFull(&S)){
            c = infix[i];
            for(i=0; infix[i]='\0'; i++){
                if(c=='('){
                        Push(infix[i], &S);
                   }else if(isalnum(c)){
                        postfix[k++] = c;
                    }else if(c==')'){
                        while(Peek(&S)!='('){
                            Pop(&postfix[k++], &S);
                            Pop(&elem, &S);
                        }
                    }else{
                        while(Oprecedence(Peek(&S))>=Oprecedence(c)){
                            Pop(postfix[k++], &S);
                            Push(&c, &S);
                    }
                }
            }
    }

    while(!IsStackEmpty(&S)){
        Pop(&postfix[k++], &S);
    }
    postfix[k] = '\0';
    printf("\nPostfix Expression = %s\n", postfix);
}

我也上传下面的问题并对其进行检查,

This is the question I have tried

enter image description here

enter image description here

0 个答案:

没有答案