how to create linked lists in c

Solutions on MaxInterview for how to create linked lists in c by the best coders in the world

showing results for - "how to create linked lists in c"
Nora
12 Apr 2018
1#include <stdio.h>
2#include <stdlib.h>
3
4// Represents a node
5typedef struct node
6{
7    int number;
8    struct node *next;
9}
10node;
11
12int main(void)
13{
14    // List of size 0. We initialize the value to NULL explicitly, so there's
15    // no garbage value for our list variable
16    node *list = NULL;
17
18    // Allocate memory for a node, n
19    node *n = malloc(sizeof(node));
20    if (n == NULL)
21    {
22        return 1;
23    }
24
25    // Set the value and pointer in our node
26    n->number = 1;
27    n->next = NULL;
28
29    // Add node n by pointing list to it, since we only have one node so far
30    list = n;
31
32    // Allocate memory for another node, and we can reuse our variable n to
33    // point to it, since list points to the first node already
34    n = malloc(sizeof(node));
35    if (n == NULL)
36    {
37        free(list);
38        return 1;
39    }
40
41    // Set the values in our new node
42    n->number = 2;
43    n->next = NULL;
44
45    // Update the pointer in our first node to point to the second node
46    list->next = n;
47
48    // Allocate memory for a third node
49    n = malloc(sizeof(node));
50    if (n == NULL)
51    {
52        // Free both of our other nodes
53        free(list->next);
54        free(list);
55        return 1;
56    }
57    n->number = 3;
58    n->next = NULL;
59
60    // Follow the next pointer of the list to the second node, and update
61    // the next pointer there to point to n
62    list->next->next = n;
63
64    // Print list using a loop, by using a temporary variable, tmp, to point
65    // to list, the first node. Then, every time we go over the loop, we use
66    // tmp = tmp->next to update our temporary pointer to the next node. We
67    // keep going as long as tmp points to somewhere, stopping when we get to
68    // the last node and tmp->next is null.
69    for (node *tmp = list; tmp != NULL; tmp = tmp->next)
70    {
71        printf("%i\n", tmp->number);
72    }
73
74    // Free list, by using a while loop and a temporary variable to point
75    // to the next node before freeing the current one
76    while (list != NULL)
77    {
78        // We point to the next node first
79        node *tmp = list->next;
80        // Then, we can free the first node
81        free(list);
82        // Now we can set the list to point to the next node
83        list = tmp;
84        // If list is null, when there are no nodes left, our while loop will stop
85    }
86}
87