【问题标题】:How can I display every element in this stack struct? (C)如何显示此堆栈结构中的每个元素? (C)
【发布时间】:2021-09-13 16:48:02
【问题描述】:

我目前正在处理一项作业,其中一个问题涉及堆栈结构。我找到了一个合适的结构(单链表结构),但是我不确定如何显示堆栈中的每个元素,因为它使用了多个结构。

struct stack_entry {
    char *data;
    struct stack_entry *next;
};

struct stack_t { 
    struct stack_entry *head;
    size_t stack_size;
};

struct stack_t *newStack(void) { 
    struct stack_t *stack = malloc(sizeof *stack);
    if (stack) {
        stack->head = NULL;
        stack->stack_size = 1;
    }
    return stack;
}

到目前为止,我已经编写了这个函数 - 但是它当然不起作用,至少我很难说。

void display(struct stack_t *stack) { //displays all of the entries of the stack
    for (int i = 0; i < stack->stack_size; i++) {
        char *tmp = stack->head[i].data;
        printf("%s ", tmp);
    }
}

【问题讨论】:

  • 这个stack 看起来很像linked list
  • 无关:为什么新创建的stack_t 的大小为1 而不是0
  • 部分问题指出堆栈必须始终包含至少一个条目,因此为什么将大小初始化为 1 而不是 0。我知道乍一看可能会令人困惑哈哈哈
  • 确实如此。 :-) 如果它必须包含至少一个条目,您可能还应该创建那个条目?
  • 另外,感谢您的快速回复和回答;它对我帮助很大:-)

标签: c struct stack


【解决方案1】:

head 是指向第一个struct stack_entry 的指针,每个struct stack_entry 都有一个next 指针。

char *tmp = stack-&gt;head[i].data; 尝试将 head 用作数组,这将导致未定义的行为。

您需要跟随指针(链接)直到到达NULL 指针。

例子:

void display(struct stack_t *stack) { //displays all of the entries of the stack
    for(struct stack_entry *curr = stack->head; curr; curr = curr->next) {
        printf("%s ", curr->data);
    }
}

【讨论】:

    【解决方案2】:

    您可以尝试这样的事情(扫描列表):

    void display(struct stack_t *stack)
     { struct stack_entry *pEntry;  // current entry
       pEntry = stack->head;   
       while (pEntry != NULL)    
        { char *tmp = stack->head[i].data;
          printf("%s ", tmp);
          pEntry = pEntry->next;  // next element of list
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-03
      • 2012-06-10
      • 2011-01-03
      • 2011-04-20
      • 2023-04-06
      • 2020-09-11
      • 2021-02-06
      • 2016-06-29
      相关资源
      最近更新 更多