乌克大喵喵 发表于 2019-7-19 16:47:29

小白求助,这个逆波兰算法的push和pop为什么运行不了

学了半个月的c语言。我们学校的一道考试题,其中push()和pop()还有free_stack()是自己写的,free_stack()的作用是如果栈为空的场合返回真,如果不是,则释放所有栈的元素并返回假。

push()的话我想用*sp指向新建的*n为什么说是NULL值不能用??



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

#define NULL ((void *)0)
#define OK 1
#define ERROR 0

extern int error;

struct element
{
        struct element *next;
        int data;

};

struct element *sp = NULL;
int error = 0;

void push(int x) {
        struct element *n;
        n = malloc(sizeof(struct element));
        *sp->next = *n;
        n->data=x;
        *sp = *n;
}

int free_stack() {
        if (sp==0)
                return OK;
        else
                return ERROR;
}

int pop() {
        int x;
        struct element *f;
        if (!sp) {
                error = 1;
                return(0);
        }
        x = sp->data;
        f = sp;
        sp=sp--;
        free(f);
        return(x);

}

void init_stack() {
        free_stack();
        sp = NULL;
        error = 0;
}



void do_num(char *s) {
        int a;
        a = atoi(s);
        push(a);
}

void do_add() {
        int a, b;
        b = pop();
        a = pop();
        push(a + b);
}

void do_sub() {
        int a, b;
        b = pop();
        a = pop();
        push(a - b);
}

void do_eq() {
        int a, b;
        b = pop();
        a = pop();
        push(a == b);
}

void do_not() {
        int a;
        a = pop();
        push(!a);
}

void do_cond() {
        int a, b, c;
        c = pop();
        b = pop();
        a = pop();
        if (a)
                push(b);
        else
                push(c);
}


int calc(char *exp[], int *xp) {
        init_stack();
        for (int i = 0; exp != NULL; i++) {
                if (isdigit(exp))
                        do_num(exp);
                else if (strcmp(exp, "+") == 0)
                        do_add();
                else if (strcmp(exp, "-") == 0)
                        do_sub();
                else if (strcmp(exp, "==") == 0)
                        do_eq();
                else if (strcmp(exp, "!") == 0)
                        do_not();
                else if (strcmp(exp, "?") == 0)
                        do_cond();
                else {
                        free_stack();
                        return(ERROR);
                }
        }

        *xp = pop();
        free_stack();
        if (error)
                return(ERROR);
        else
                return(OK);

}

int main() {
        int x = 0;
        char *exp[] = { "30","50","+",NULL };
        if (calc(exp, &x) == OK)
                printf("the result is %d\n", x);
        else
                printf("Error\n");
        return(0);
       
}

AmosAlbert 发表于 2019-8-1 21:21:51

#define NULL ((void *)0)重定义了, n = malloc(sizeof(struct element));并且整型与指针型数据的转换错误
页: [1]
查看完整版本: 小白求助,这个逆波兰算法的push和pop为什么运行不了