如何显示此堆栈结构中的每个元素? (C)
How can I display every element in this stack struct? (C)
我目前正在做作业,其中一个问题涉及堆栈结构。我找到了一个合适的结构(单链表结构),但是我不确定如何显示堆栈中的每个元素,因为它使用了多个结构。
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);
}
}
head
是指向第一个 struct stack_entry
的指针,每个 struct stack_entry
都有一个 next
指针。
char *tmp = stack->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);
}
}
您可以尝试这样的事情(扫描列表):
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
}
}
我目前正在做作业,其中一个问题涉及堆栈结构。我找到了一个合适的结构(单链表结构),但是我不确定如何显示堆栈中的每个元素,因为它使用了多个结构。
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);
}
}
head
是指向第一个 struct stack_entry
的指针,每个 struct stack_entry
都有一个 next
指针。
char *tmp = stack->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);
}
}
您可以尝试这样的事情(扫描列表):
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
}
}