Initialize a linked list using ints in C

随声附和 提交于 2019-12-12 07:05:12

问题


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

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


回答1:


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;

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.

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".



来源:https://stackoverflow.com/questions/32636142/initialize-a-linked-list-using-ints-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!