This is code for a linked list in the C programming language.
#include <stdio.h> /* For printf */
#include <stdlib.h> /* For malloc */
typedef struct node {
int data;
struct node *next; /* Pointer to next element in list */
} LLIST;
LLIST *list_add(LLIST **p, int i);
void list_remove(LLIST **p);
LLIST **list_search(LLIST **n, int i);
void list_print(LLIST *n);
The code is not completed, but I think it’s enough for my question. Here at the end of struct node “LLIST” is used, and it’s also used as a return type in the prototyping of the function list_add. What is going on?
typedefcreates a new “type” in your program, so the return value and types of parameters of those functions are just your struct. It is just shorthand for usingstruct nodefor the type.If you were to create a new node, you could do it like this (using the type):
Also, with the function prototypes in your question, you don’t really need the double pointers; since the data in your struct is just an
int, you could do something likethen the
list_addfunction would handle the allocation, copy theintinto the struct and add it to the linked list.Putting it in at a certain position is as simple as changing the
nextpointer in the node before it to the address of the newly allocated node, and thenextpointer in the new node to point at the next one (the one the node before that one was originally pointing at).Keep in mind that (given the rest of your function prototypes) you will have to keep track of pointers to every node you create in order to delete them all.
I’m not sure I understand how the search function will work. This whole thing could be implemented a lot better. You shouldn’t have to provide the location of a node when you create it (what if you specify a higher number than there are nodes?), etc.