我的程序应该读取后缀表达式,并使用树实现将其转换为infix和前缀。pop()方法总是给出第一个元素,而不对其进行擦除,我不知道原因。任何帮助都是可以接受的。
//tree structur
typedef struct asa {
enum { number_exp,sous_exp_op } type;
union {
int child;
struct {
struct asa* left;
struct asa* right;
char oper; } tree;
} op;
} asa;
//stack
typedef struct stack {
int size;
struct {
asa * element;
struct stack* link;
}e;
} stack;
struct stack *top;
(...)
asa * pop(){
asa* e ;
stack * temp;
if(top->size == 0 ){
printf("ERR0R : empty stack\n");
exit (EXIT_FAILURE);
}
else if (top->size >= 1){
temp = top->e.link;
e= top->e.element;
top = temp;
}
return e;
}
void push(asa* node ){
if(top->size == 0 ){
top->e.element = node;
top->e.link = NULL;
top->size++;
}
else if (top->size > 0){
pile * next = (pile*) malloc(sizeof(top));
next = top;
top->e.element = node;
top->e.link = next;
top->size++;
}
}日志快照:

发布于 2012-11-18 07:23:31
您当前面临的问题是,在分配next时,您会立即放弃top->size > 0,而不是为整个结构分配指针的大小。要修复它们,请将next = top替换为函数末尾的top = next,并修复sizeof调用:
else if (top->size > 0){
pile * next = (pile*) malloc(sizeof(*top));
next->e.element = node;
next->e.link = top;
next->size = top->size + 1;
top = next;
}而且,这种堆栈的实现感到不必要的复杂和容易出错.如果需要堆栈大小,则应独立于链接列表的节点保持大小,而不是在每个单独的节点中。标准的链接列表成语是将空列表(堆栈)表示为NULL,所以push和pop不需要任何额外的代码来检查空堆栈:
typedef struct stack {
asa *element;
struct stack *next;
} stack;
void push(stack **head, asa *elem)
{
stack *new_head = malloc(sizeof(stack));
new_head->next = head;
new_head->elem = elem;
*head = new_head;
}
asa *pop(stack **head)
{
stack *old_head = *head;
asa *top_elem = old_head->elem;
*head = old_head->next;
free(old_head);
return top_elem;
}https://stackoverflow.com/questions/13437423
复制相似问题