DEV Community

Michael Otieno Olang
Michael Otieno Olang

Posted on

5 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay