gpt4 book ai didi

c - 链表在开头打印额外的 0

转载 作者:行者123 更新时间:2023-12-02 05:58:39 24 4
gpt4 key购买 nike

我有一个非常基本的单链表实现。然而,我的实现的问题是它在列表的开头打印了一个额外的零,而我没有明确地为这个额外的节点分配任何存储空间。相同的代码如下 -

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define LEN 7

/* List node data structure */
typedef struct _ll_node_ {
int data;
struct _ll_node_ *next;
} node;

/*
* @brief Utility to print the state of the list
*/
void print_list(node *head)
{
int i = 0;
node *tmp = head;
while (tmp)
{
printf("Node:\t%d,\tValue:\t%d\n", ++i, tmp->data);
tmp = tmp->next;
}
printf("\n");
}

/*
* @brief Utility to add nodes to the list
*/
node *add_node(node *head, int data)
{
node *tmp;
if (head == NULL)
{
head = malloc(sizeof(node));
assert(head != NULL);
head->data = data;
head->next = NULL;
}
else
{
tmp = head;
while (tmp->next)
tmp = tmp->next;
tmp->next = malloc(sizeof(node));
assert(tmp->next != NULL);
tmp = tmp->next;
tmp->data = data;
tmp->next = NULL;
}
return head;
}

/*
* @brief Driver function
*/
int main(int argc, char *argv[])
{
node *head = NULL;
int i = 0;
/* Allocate memory */
head = malloc(LEN * sizeof(node));
assert(head != NULL);
/* Populate the list */
for (; i < LEN; i++)
head = add_node(head, rand() % 1000);
/* Print its state */
print_list(head);

return 0;
}

谁能帮我弄清楚我哪里做错了?

System information:
Distributor ID: Ubuntu
Description: Ubuntu 14.04.3 LTS
Release: 14.04
Codename: trusty

最佳答案

您已经在 main 中为 head 分配内存,因此永远不会为第一个节点分配数据,因此默认情况下它将它设为 0。试试这个:

int main(int argc, char *argv[])
{
node *head = NULL;
int i = 0;

/* Populate the list */
for (; i < LEN; i++)
head = add_node(head, rand() % 1000);
/* Print its state */
print_list(head);

return 0;
}

关于c - 链表在开头打印额外的 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com