Pop()方法始终从堆栈中提供第一个元素而不擦除它

时间:2012-11-18 04:13:56

标签: c tree stack expression

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

记录快照:

enter image description here

1 个答案:

答案 0 :(得分:1)

您当前的问题是,在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; } 调用:

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;
}

此外,堆栈的这种实现感觉不必要地复杂且容易出错。如果需要堆栈大小,则应该独立于链接列表的节点而不是每个单独的节点保持大小。标准链表成语是将空列表(堆栈)表示为NULL,因此push和pop都不需要任何额外的代码来检查空栈:

{{1}}