我已经花了大约 7 个小时试图让它自己工作,但我无法弄清楚。通过我之前的测试,我能够成功地将我的 char[] 的所有值完全压入堆栈,并且我可以正确地弹出它们并返回值。 但是,如果我尝试将某些内容推回堆栈,那么整个程序就会崩溃。
注意事项:
该代码应该用于稍后为表达式树创建节点
switch 语句中注释掉的代码是我在发生错误时的代码,只是保存它以备我可以修复它时使用。
-使用pop后push时,该函数被正确调用,但是它没有进入push中的if或else语句。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Stack;
typedef struct StackNode;
typedef struct StackPtr;
struct StackPtr
{
struct StackPtr *prev;
struct StackNode *ptr;
};
struct StackNode
{
char c;
struct StackNode *lchild;
struct StackNode *rchild;
};
struct Stack
{
struct StackPtr *top;
};
// Prototypes
void initStack(struct Stack*);
struct StackNode* createNode(char);
struct StackNode* pop(struct Stack*);
void push(struct Stack*, struct StackNode*);
int isEmpty(struct Stack*);
int main()
{
struct Stack *s = malloc(sizeof(s));
initStack(s);
char exp[7] = "45+67+*";
int length = 0;
for(length; length<3; length++) // push the expression onto the stack
{
struct StackNode *exp1 = malloc(sizeof(exp1));
struct StackNode *exp2 = malloc(sizeof(exp2));
struct StackNode *c = malloc(sizeof(c));
if(exp[length] > 47 && exp[length] < 58) // is a number
{
c->c = exp[length];
push(s,c);
}
else
{
switch(exp[length])
{
default:
printf("exp[length] error\n");
break;
case '+':
exp2 = pop(s);
exp1 = pop(s);
c->c = '7';
push(s, c);
//push(s, exp1->ptr);
//push(s, exp2->ptr);
//c->c = exp[length];
//c->rchild = exp2;
//c->lchild = exp1;
//printf("test ");
//push(s, c);
//printf("test ");
break;
case '-':
break;
case '*':
break;
case '/':
break;
}
}
}
return 0;
}
void initStack(struct Stack *s)
{
struct StackNode *n = malloc(sizeof(n));
struct StackPtr *p = malloc(sizeof(p));
n->c = NULL;
n->lchild = NULL;
n->rchild = NULL;
p->prev = NULL;
p->ptr = n;
s->top = p;
}
struct StackNode* createNode(char c)
{
struct StackNode *n = malloc(sizeof(n));
n->c = c;
n->lchild = NULL;
n->rchild = NULL;
return n;
}
void push(struct Stack *s, struct StackNode *n)
{
if(s->top->ptr->c == NULL) // First item being pushed
{
s->top->ptr = n;
printf("1Added: %c to the stack\n", n->c);
}
else
{
struct StackPtr *o = malloc(sizeof(o));
o->prev = s->top;
s->top = o;
s->top->ptr = n;
printf("2Added: %c to the stack\n", n->c);
}
}
struct StackNode* pop(struct Stack *s)
{
if(isEmpty(s) == 1)
{
printf("Stack is empty!\n");
return;
}
else
{
struct StackPtr *tmp = malloc(sizeof(tmp));
tmp = s->top;
s->top = s->top->prev;
printf("Popped: %c from the stack.\n",tmp->ptr->c);
return tmp->ptr;
}
}
int isEmpty(struct Stack *s)
{
if(s->top == NULL)
return 1;
else
return 0; // false
最佳答案
您的POP
功能正在设置
s->top = s->top->prev;
弹出两个节点后,Prev 值为 NULL,因此 top 指向 NULL,这导致下一个 PUSH
还有一些事情需要考虑,将值更改为 8 而不是 7,因为\0 需要适合。或将其用作 字符表达式[]
char exp[8] = "45+67+*";
关于使用pop后无法推送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26367717/