gpt4 book ai didi

c - 在C中使用int初始化链表

转载 作者:行者123 更新时间:2023-11-30 19:15:25 26 4
gpt4 key购买 nike

我需要使用 main.c 中给出的整数来初始化一个链表。

#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;
}

我只是不知道如何使用整数初始化链表。谢谢。

最佳答案

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

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

struct node *head = NULL;

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

记住:大多数指针仅指向现有数据。无需为此类指针分配内存。并确保始终正确初始化指针;它们应该要么指向有效的内存,要么为 NULL 表示“不指向任何东西”。

关于c - 在C中使用int初始化链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636142/

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