나는 매우 기본적인 단독 링크 목록 구현을 가지고 있습니다. 그러나 구현시 문제는 목록의 시작 부분에 여분의 0을 인쇄하는 반면 명시 적으로이 추가 노드에 대한 저장소를 할당하지 않는다는 것입니다. 같은 코드는 다음과 같습니다 -링크 된 목록은 처음에 여분의 0을 인쇄합니다.
#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
이 두 줄의 주석은 다음과 같습니다. head = malloc (LEN * sizeof (node)); assert (head! = NULL);'나머지는 모두 정상입니다. –