使用C中的ints初始化链接列表

时间:2015-09-17 17:08:52

标签: c linked-list 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;
} 

我无法看到如何使用整数初始化链表。谢谢。

1 个答案:

答案 0 :(得分:1)

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

现在您要初始化列表以使其可用。默认状态是空列表,即没有任何节点的列表。所以你做的就是分配内存。就这样做:

struct node *head = NULL;

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

请记住:大多数指针只指向现有数据。没有必要为这样的指针分配内存。并确保始终正确初始化指针;他们应该指向有效的记忆,或者NULL表示“不指向任何东西”。

相关问题