0

我的程序应该读取后缀表达式并使用树实现将其转换为中缀和前缀。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++;
    }
}

日志快照:

在此处输入图像描述

4

1 回答 1

1

您的直接问题是,next一旦分配它,您就会丢弃它,top->size > 0并且您正在为指针而不是整个结构分配大小。要修复它们,请在函数末尾替换为并修复next = top调用:top = nextsizeof

    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;
}
于 2012-11-18T07:23:31.993 回答