×

What is Linked List in C

Linked list

Similar to an array, a linked list is a linear data structure that stores a chain of nodes with two fields of memory in each node. Where first memory is used for data, and second memory is used to store the addresses of subsequent components.

Therefore, each struct node in a linked list has two memory fields: a data field and an address field.

The address field contains the address of the next element. The address section is also known as Pointer to the Next Node.

After array, we use linked list as our second priority for the data structure.

The linked list's size is not defined, and data items may be inserted along the list.

Linked list Vs. Array:

The fundamental distinction between an array and a linked list is the amount of contiguous memory that an array takes up as opposed to the dispersed memory of a linked list.

Random access is made feasible by the array's contiguous memory. Any element can be directly accessed using its index. The below table explains more about the differences between Linked List and Array:

S.no.Linked ListArray
1A linked list is a linear data structure which consist of a series of nodes. We can store data and also address of next node in every node.     An array is also a linear type of data structure which consists of similar data types elements in contiguous memory location.    
2Memory is dispersed in Linked List. In physical memory, the nodes are organized in random order.  An array takes up contiguous memory. This indicates that the data is kept in physical memory's subsequent memory locations.  
3Access to the sequence is supported by linked lists. It implies that we must read nodes progressively starting at the beginning of the list to access any random node. The reason for this is that physical memory nodes are scattered at random. Nodes, unlike arrays, do not have a known address.  Random access is possible with arrays. The array's elements can be accessed directly by their indexes. Since the data is kept in a single, continuous memory space, we can quickly access any element of an array using its index.  
4Each node in a linked list has two memory fields: one for data and one for the address of the next node. This means that Linked List takes up more memory than an array.  The array merely stores the data at each index. Nothing additional is kept in storage.
5It's easy to insert or delete. Nodes aren't moved around or rearranged as a result of it.  Rearranging all of the array's members may be necessary to insert or remove data from it.  
6Memory is efficiently used by Linked List. Only when data is added does it take up memory.  Even without any data being inserted, an array uses memory.  
7The memory for the linked list is allocated at runtime.An array may have memory allocated for it both during compilation and during runtime.  
8Linked List is dynamic. Its size is freely expandable and contractible.  The array that has allocated memory at compile time is a static array that has been declared, and its size is fixed.  
9On a linked list, we cannot conduct a binary search.  On the array, we can conduct a binary search.    

Types of linked lists:

  1. Singly Linked List
  2. Doubly Linked List

Singly Linked List:

The most prevalent kind of linked list among all other linked lists is the singly linked list. We can only navigate in one direction in a singly linked list. It is an assortment of sets of elements in an orderly fashion. In single linked list, each node in a linked list has two memory fields: one for data and one for the address of the next node.

A singly linked list can be created in essentially two different methods, which are: 

  • We can add any future new entries to the linked list's end.
  • The alternative is to insert items into particular locations in the list in ascending order of sorted items.

Each item in a linked list must have both the data and an address of the next item in the list. The items contained in a linked list typically consist of structures.

What is Linked List in C

Syntax:

struct node
{
Int data;
struct node * after;
};

In the above syntax, struct nodes are used to hold data of the integer type and struct nodes *, which hold the address of the next node.

In singly linked lists, there is a single node connected just next to another node, so in the above code, we have used a struct to describe a node. The node will contain its integer value and the pointer of the same node type to the next.

Example: Let's create a singly linked list of node size 4 where the node order would be 4->1->2->3.

C code:

#include<stdio.h>
#include<stdlib.h>


struct node{
    int data;
    struct node* after_node;
};


int main(){
    struct node* one=NULL;
    struct node* two=NULL;
    struct node* three=NULL;
    struct node* four=NULL;
    
    one=(struct node*)malloc(sizeof(struct node));
    two=(struct node*)malloc(sizeof(struct node));
    three=(struct node*)malloc(sizeof(struct node));
    four=(struct node*)malloc(sizeof(struct node));
    
    one->data=4;
    one->after_node=two;
    
    two->data=1;
    two->after_node=three;
    
    three->data=2;
    three->after_node=four;
    
    four->data=3;
    four->after_node=NULL;
    
    struct node* temp = one;
    while(temp!=NULL){
        printf("%d ",temp->data);
        temp=temp->after_node;
    }
}

Program Output:

What is Linked List in C

Explanation:

In the above c code, we created four variables of type struct and initialized them as NULL. Now in the first node, we put the value, and we initialize its next node as a pointer that points to the next node. Now in the second node, we put the value again, and the next pointer would point to the third node. Now the third node will contain a value, and it will point to the fourth node as its next pointer since the fourth pointer is the last pointer so that we will put the value into it, and its next pointer will point to NULL.

Time complexity:

Search: O(N)

insertion: O(1)

deletion: O(1)

Doubly Linked list:

A data portion and two pointers—one for the previous node and the other for the next node—are contained in each node in a doubly-linked list.

In a doubly linked list, there are two possible directions of movement: forward and backward.

Traversal is possible in both directions using a doubly linked list. The next node's and the previous node's addresses are available. The choice to turn right or left will be available at any node.

Data, a pointer to the subsequent node, and a pointer to the preceding node make up a node.

With NULL as the previous node refers that the head node is empty. See the below image:

What is Linked List in C

Example: We will be having an example of a doubly linked list:

NULL <-> 4 <-> 6 <-> 9 <-> 5 <-> 3 <-> NULL

C code:

#include<stdio.h>
#include<stdlib.h>


struct node{
    int data;
    struct node* next;
    struct node* prev;
};


void addFront( struct node** headRef,int data){
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    
    newNode->next=(*headRef);
    newNode->prev=NULL;
    
    if((*headRef)!=NULL)
    (*headRef)->prev=newNode;
    
    (*headRef) = newNode;
}


void addAfter(struct node* currNode,int data){
    if(currNode==NULL){
        printf("can't be null node");
        return;
    }
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    
    newNode->next=currNode->next;
    currNode->next=newNode;
    newNode->prev=currNode;
    if(newNode->next!=NULL){
        newNode->next->prev=newNode;
    }
}


void addEnd(struct node** headRef,int data){
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    
    newNode->next=NULL;
    
    struct node* temp=(*headRef);
    if((*headRef)==NULL){
        newNode->prev=NULL;
        (*headRef)=newNode;
        return;
    }
    
    while(temp->next!=NULL){
        temp=temp->next;
    }
    temp->next=newNode;
    newNode->prev=temp;
    
}


int main(){
    struct node* head=NULL;
    
    addFront(&head,9);
    addFront(&head,6);
    addFront(&head,4);
    addEnd(&head,3);
    addAfter(head->next->next,5);
    
    struct node* temp = head;
    struct node* last=NULL;
    printf(" left to right traversal is :");
    while(temp!=NULL){
        last=temp;
        printf("%d ",temp->data);
        temp=temp->next;
    }
    
     printf(" \nright to left traversal is :");
    while(last!=NULL){
        printf("%d ",last->data);
        last=last->prev;
    }
}

Program output:

What is Linked List in C

Explanation:

In the above code, we have a node variable of type struct where three members are present. One is the node's data, and the other two are pointers to the node before it and the node after it.

We implemented three functions that add the new node at different positions.

One function will add the new node at the start of the list. We will be given the pointer to the head and the integer data. We will create the node with data value and add it to the previous head node, making this new node the head node.

The second function will add the node after any given node. We will receive an integer value and a reference to the target node. We will create the node with its values, and then we will traverse it to the target node. The target node's next node will be the new node, and vice versa. We will add the new node as the target node's next node. Also, we will set the previous nodes also.

The final node will be added to the linked list in the third function. The list will be repeated several times, and when it is finished, the previous node of the new node will serve as the last node, with the next node of the last node added as a new node.


Related Topics

How to open a C file on android mobile

A C file is a file that has a .c extension and contains code written in the C language. C is a computer programming language developed by Dennis Ritchie at...

4 minutes read.

Add two numbers using the function in C

Here we will learn how to add two numbers by creating function in C. Let’s learn this with help of example. Code: - #include <stdio.h> int add_two_no(int a, int b); int main(){   int first_num,...

1 minute read.

Else If Ladder in C

What is Else If Ladder: When there are multiple options and a user has to decide from the options, we use Else If Ladder. Basically, it is an extension of if...

3 minutes read.

memcmp() in C

Introduction: In this article we are discuss about memcmp() function in C. This function permits the person to evaluate the bytes of the two characters, as mentioned above. Depending on...

4 minutes read.

Results of Comparison Operations in C and C++

In this tutorial, we will explore comparison operators and how the system should compare an incoming value supplied as a context parameter to a given value or range of values. A...

2 minutes read.

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

C Program Swap Numbers in cyclic order Using Call by Reference

The three integers that the user entered in cyclical sequence are swapped in this tutorial using call by reference. C Program: #include <stdio.h> void cyclic_Swap ( int *X, int *Y, int *Z ); int...

2 minutes read.

Array Of Structures in C

The C programming language allows us to store multiple elements of the same type in arrays. We can use strings to store multiple elements of a character data type. Still,...

4 minutes read.

Pyramid Pattern in C

Pyramid Pattern in C A pyramid is a polyhedron created by connecting a base that will be a polygon, and all the lateral faces are triangles. All the bases are connected...

5 minutes read.

Find reverse of an array in C using functions

Introduction: Here, we describe how to find the reverse array in C using functions. Suppose you have an array with n elements. I need to display the elements present in...

3 minutes read.

Calendar application in C

Introduction to the calendar application We all are familiar with the calendar. It plays a crucial role in our daily life. We run toward the calendar whenever we want to know...

6 minutes read.

Advantages of Dynamic Memory Allocation in C

Dynamic Memory Allocation Dynamic memory allocation is a process of assigning or allocating memory to a variable during the execution of a program. Dynamic memory allocation provides storage according to the...

3 minutes read.

Decimal to Binary in C

What is a decimal number? A decimal number is a number represented in the decimal number system. This system of binary conversion uses base 10 to represent numbers, i.e. the digits...

3 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it shows...

4 minutes read.

What is Linked List in C

Linked list Similar to an array, a linked list is a linear data structure that stores a chain of nodes with two fields of memory in each node. Where first memory...

7 minutes read.

GCD program in C

C language : Dennis Ritchie developed the general-purpose computer language C at Bell Laboratories in 1972. Despite being an ancient language, it is extremely popular. It is among the most widely used...

4 minutes read.

Use of free() function in C

Introduction The free() function uses in C programming language. The free() function in the C programming language uses to release or deallocate the memory blocks; these blocks are previously allocated by calloc(), malloc() or realloc()...

3 minutes read.

Armstrong Number in C

The Armstrong number is defined as the sum of each of its digits to the power of the number base for the each given number with any given number base....

3 minutes read.

Pointer to pointer in C

A pointer to another pointer is another type of multiple indirections and a chain of many pointers. Generally, a pointer consists of the address of the variable. Once a pointer to...

4 minutes read.

Infix to Postfix program in C

Infix Expression: In infix expression, an operator is placed between the two operands. Example: x + y, here operator + is placed between operands x and y. Postfix Expression: In...

3 minutes read.