使用C中的int初始化链表 [英] Initialize a linked list using ints in C

查看:114
本文介绍了使用C中的int初始化链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用main.c给出的int初始化链表.

I need to initialize a linked list using ints given from the 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

我知道我所拥有的是不正确的,但这是我能提出的最好的答案.

I know what I have isn't correct, but it's the best I could come up with.

#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初始化链表.谢谢.

I just cannot see how to initialize the linked list using the ints. Thank you.

推荐答案

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

Your list is described by a pointer to its head element.

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

Now you want to initialise the list so that it is usable. The default state is an empty list, i.e. one that does not have any nodes. So what you don't do is to allocate memory. Just do this:

struct node *head = NULL;

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

You have a NULL head, which means that you don't have any elements. When you add nodes, you create them with malloc and assign them via this pointer. If the head is NULL, it must be updated to point to the first node, whose next member must be NULL.

请记住:大多数指针仅指向现有数据.无需将内存分配给此类指针.并确保始终正确初始化指针;它们应该指向有效内存,或者为NULL表示不指向任何内容".

Remember: Most pointers just point to existing data. There's no need to allocate memory to such pointers. And make sure to always initialise pointers properly; they should either point to valid memory or be NULL to mean "not pointing to anything".

这篇关于使用C中的int初始化链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆