双指针 C 表示列表



不久前我开始学习c。当我尝试编码列表时,我用双指针编写了函数,因为我在其他资源中看到了这一点,然后我自己完成了这个函数的编写,但它不起作用,请帮助我并解释它是如何工作的。

void
push(v_stack_t ** node, int num_args, ...)
{
va_list ap;
v_stack_t **current = node;
va_start(ap, num_args);
for (int i = 0; i < num_args; i++) {
v_stack_t *new_node = (v_stack_t *) malloc(sizeof(v_stack_t));
new_node->value = va_arg(ap, int);
if (*current == NULL) {
*current = new_node;
continue;
}
while ((*current)->next != NULL) {
current = &(*current)->next;
}
(*current)->next = new_node;
}
va_end(ap);
}

您还没有向我们展示v_stack_t的定义,但是在分配一个结构后,您不会初始化该结构的所有成员。new_node->next中将有一些未知值(可能不是 NULL(,当您尝试添加第二个节点时会导致问题。 你应该设置

new_node->next = NULL;

紧接着malloc声明。

不相关,您不需要从malloc强制转换返回值。

正如1201ProgramAlarm提到的,您需要将next设置为NULL

但是,因为你使用current,它的最终值永远不会传播回调用者(例如,你需要在最后设置*node(。

您的内while环可以移动到外环上方。

而且,在开始时取消引用node并对大部分函数使用单个间接指针要容易得多。旁注:head比这里node更能描述功能。

下面是代码的返工:

void
push(v_stack_t **head, int num_args, ...)
{
va_list ap;
v_stack_t *tail;
// find last element of list
tail = NULL;
for (v_stack_t *cur = *head;  cur != NULL;  cur = cur->next)
tail = cur;
va_start(ap, num_args);
for (int i = 0; i < num_args; i++) {
v_stack_t *new_node = malloc(sizeof(v_stack_t));
new_node->value = va_arg(ap, int);
new_node->next = NULL;
// append to tail of list
if (tail != NULL)
tail->next = new_node;
// add node at head of list
else
*head = new_node;
// set new element as tail of list
tail = new_node;
}
va_end(ap);
}

最新更新