Creating a simple Linked List In C programming

mikeyolang

Michael Otieno Olang

Posted on November 17, 2022

Creating a simple Linked List In C programming

Linked Lists are list of elements in which the various elements are linked together. Data in a linked list are stored in a linear manner. The Data are placed in nodes and the nodes are connected in a specific desired fashion.
Node is a container or a box which contains data and other information in it. In a list a node is connected to a different node forming a chain of nodes.
The first step in making a linked list is making a node which will store data into it.
C program for a Linked List
We first create a structure named node which stores an integer named data and a pointer named next to another structure (node).

struct node
{
    int data;
    struct node *next;
};
Enter fullscreen mode Exit fullscreen mode

We then make two nodes (structure named node) and allocating space to them using the malloc function.

struct node *a, *b;
    a = malloc(sizeof(struct node));
    b = malloc(sizeof(struct node));
Enter fullscreen mode Exit fullscreen mode

We then set the values of data of the nodes a and b.

    a->data = 10;
    b->data = 20;
Enter fullscreen mode Exit fullscreen mode

We then store the address of b in the next variable of a. Thus, next of a is now storing the address of b or we can say the next of a is pointing to b.Since there is no node for the next of b, so we are making next of b null.

    a->next = b;
    b->next = NULL;
Enter fullscreen mode Exit fullscreen mode

We then Print to see the output

printf("%d\n%d\n", a->data, a->next->data);
Enter fullscreen mode Exit fullscreen mode

Below is the Combined Code

Image description

💖 💪 🙅 🚩
mikeyolang
Michael Otieno Olang

Posted on November 17, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related