在C中使用int初始化链表



我需要用main.c中给出的int值初始化一个链表。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char ** argv) 
{
     int b = 128;
     int M = b * 11;  // so we have space for 11 items
     char buf [1024];
     memset (buf, 1, 1024);     // set each byte to 1
     char * msg = "a sample message";
     Init (M,b); // initialize

我知道我写的不正确,但这是我能想出的最好的。

#include <stdio.h>
#include "linked_list.h"
struct node
{
     int value;
     struct node *next;
};
struct node* head;
struct node* tail;
void    Init (int M, int b)
{
     head = (struct node *) malloc(sizeof *head);
     tail = (struct node *) malloc(sizeof *tail);
     head->next = tail;
     tail->next = tail;
} 

我只是不明白如何使用int型初始化链表。谢谢你。

您的列表由指向其头部元素的指针描述。

现在要初始化列表,使其可用。默认状态是一个空列表,即没有任何节点。所以不应该分配内存。只需这样做:

struct node *head = NULL;

你有一个NULL头,这意味着你没有任何元素。添加节点时,使用malloc创建节点,并通过该指针对其进行分配。如果headNULL,则必须更新为指向第一个节点,其next成员必须为NULL

记住:大多数指针只是指向现有的数据。没有必要为这样的指针分配内存。确保总是正确初始化指针;它们要么指向有效的内存,要么是NULL表示"不指向任何东西"。

最新更新