|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
学了半个月的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[i] != NULL; i++) {
if (isdigit(exp[i][0]))
do_num(exp[i]);
else if (strcmp(exp[i], "+") == 0)
do_add();
else if (strcmp(exp[i], "-") == 0)
do_sub();
else if (strcmp(exp[i], "==") == 0)
do_eq();
else if (strcmp(exp[i], "!") == 0)
do_not();
else if (strcmp(exp[i], "?") == 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);
} |
|