In this tutorial, We will learn about the linked list in C, and it’s implementation. The array data structure has some limitations. Firstly, the array’s size is fixed due to which either a lot of memory is wasted if we have very few elements in the array or undesirable results are produced if the number of elements in the array exceeds the limits of the defined size. Secondly, the insertions and deletions of elements are complex and inefficient processes as potentially a large number of elements need to be shifted to make room for a new element or to delete an existing element. So to overcome these severe limitations, another data structure known as Linked List is used.
The linked list is probably the second most fundamental data structure used after arrays. Linked Lists have their strengths and weaknesses, but they happen to be strong where arrays are weak. It can replace the array as the basis for implementing other data structures such as stacks and queues. The linked list is frequently used in those situations where we have an unpredictable number of data elements, and when we want to insert and delete a large number of elements quickly.
We’ll be covering the following topics in this tutorial:
What is Linked List in C?
Linked lists in C are among the simplest and most common linear data structures. A linked list is a series of connected objects called nodes whose order isn’t provided by their physical positioning in memory. Instead, every node points to the other. Every node contains two fields, i.e., data and an address (in different phrases, a link) to the next node and forms a chain. Linked Lists are used to create trees and graphs. The last node contains a pointer to the null. The size of the linked list not fix. The structure allows for efficient removal or insertion of the node from any place in the sequence through iteration.
The linked list is usually considered as an example of a dynamic memory allocation. A drawback of linked lists is that access time is linear. Faster access, such as random access, isn’t feasible. The Linked List is similar to an array; however, it isn’t stored sequentially in the memory, unlike an array. Arrays have improved cache locality compared to linked lists.
To count the number of elements, you have to traverse through the entire list. Hence time complexity is O(n). It would be best if you had a temp variable to keep track of the current node. Therefore the space complexity is O(1).
Linked lists have a few advantages over arrays
The data structure that linked lists compete directly with is the array. Each data structure has its strengths and weaknesses. So the choice of a particular data structure depends upon the requirements of a problem. The linked list is frequently used in those situations where many insertions and deletions need to be performed, and the number of data elements may be unpredictable. Following are the key distinguishing features between linked lists and arrays.
• Insertion and deletion of an element can be performed quickly in the linked list as you need to rearrange certain pointers once the insertion/removal point is known. However, in arrays, insertion and deletion are complex and inefficient. The potentially large number of elements need to be shifted to make room for a new element or delete an existing element.
• LinkedList is a dynamic data structure as storage space is allocated dynamically. Therefore, the size of the linked list is not fixed and may expand or shrink as nodes are inserted or deleted. Thus it aims for efficient utilization of memory space and can accommodate the arbitrary number of elements per user requirements. In contrast, the array is a static data structure in which several elements are fixed. Thus either a lot of memory is wasted if we have very few elements in the array, or undesirable results are produced if the number of elements in the array exceeds the defined size limits.
• In a linked list, the time required to access any node depends on that node’s location, whereas in arrays, an element takes a constant time irrespective of its position.
• Unlike arrays, the successive nodes in the linked list need not occupy adjacent memory locations.
• Linked List can be easily joined or split compared to arrays because it simply requires changing pointers and does not require any shifting of elements.
• Unlike arrays, the linked list requires additional space for storing links that connect adjacent nodes. Moreover, overhead is involved in manipulating and managing links or pointers.
Disadvantages of Linked lists
• They utilize more memory compared to arrays due to the storage utilized by their pointers.
• Nodes at a linked list has to read in sequence from the first node.
• Nodes are saved non contiguously, significantly raising the time needed to access individual elements inside the list, particularly with a cache.
• Difficulties appear in linked lists when it comes to reverse traversing.
Representation of the linked list
• Every record of a linked list can be known as an ‘element’ or ‘node.’
• The field of every node, which comprises the next node’s address, is generally known as the ‘next link’ or ‘next pointer.’
• The ‘head’ of a list is its first node. The ‘tail’ of the list denotes the last node.
Singly-linked list in C
Singly-linked lists contain nodes with a data field and a ‘next’ field, which points to the next node in a line of nodes. Operations that can perform on singly-linked lists include insertion, deletion, and traversal.
The singly linked list could traverse only in one direction. We can say that every node contains only the next pointer. Therefore we can’t traverse the list in the opposite direction.
Consider an example in which the team’s scores are stored in a linked list, as shown in the figure.
In the preceding figure, the arrow represents the links. The data part of each node includes the scores obtained by the team. The null pointer identifies the last node in the list within the address part of the final node. We could have as many nodes as we require in the data part of the list.
Complexity table
Node Creation
Let’s define a linked list node:
// A linked list node
struct Node {
int data;
struct Node* next;
};
Linked List Program in C
Let us create a simple linked list in C.
#include<stdio.h> #include<malloc.h> #include<conio.h> #include <stdlib.h> struct list { int info; struct list *link; }; struct list start,*temp,*prev,*node; void insert() { int i,j,item; printf("Enter the item to insert = "); scanf("%d",&item); printf("\n 1.Insertion at begining : "); printf("\n 2.Insertion at end : "); printf("\n 3.Insertion at middle : "); printf("\n Enter your choice = "); scanf("%d",&i); switch(i) { case 1:if(start.link==NULL) { node=(struct list *)malloc(sizeof(struct list)); node->info=item; node->link=NULL; start.link=node; return; } else { node=(struct list *)malloc(sizeof(struct list)); node->info=item; node->link=start.link; start.link=node; return; } case 2:if(start.link==NULL) { node=(struct list *)malloc(sizeof(struct list)); node->info=item; node->link=NULL; start.link=node; return; } else { temp=start.link; while(temp->link!=NULL) { temp=temp->link; } node=(struct list *)malloc(sizeof(struct list)); temp->link=node; return; } case 3:printf("Enter position = "){ scanf("%d",&j); if(start.link==NULL) { node=(struct list *)malloc(sizeof(struct list)); node->info=item; node->link=NULL; start.link=node; return; } else { temp=start.link; while(temp->link!=NULL) { if(temp->info==j) { break; } temp=temp->link; } node=(struct list*)malloc(sizeof(struct list)); temp->link=node; return; } default:printf("Wrong choice"); } } int del() { int i,j,item; printf("/n1.Deletion at beginning : "); printf("/n2.Deletion at end : "); printf("/n3.Deletion at middle : "); printf("Enter the choice : "); scanf("%d",&i); switch(i) { case 1:if(start.link==NULL) { printf("List empty"); return 0; } else { temp=start.link; item=temp->info; start.link=temp->link; free(temp); return item; } case 2:if(start.link==NULL) { printf("List empty"); return 0; } else { temp=start.link; prev=&start; while(temp->link!=NULL) { temp=temp->link; prev=prev->link; } item=temp->info; prev->link=NULL; free(temp); return item; } case 3:if(start.link==NULL) { printf("List empty"); return 0; } else { printf("Enter the item to be deleted"); scanf("%d",&i); temp=start.link; prev=&start; while(temp->link!=NULL) { if(temp->info==i) { break; } prev=prev->link; temp=temp->link; } if(temp->link==NULL) { printf("Item not available"); return 0; } else { item=temp->info; prev->link=temp->link; free(temp); return item; } } default:printf("wrong choice"); } } void display() { temp=start.link; while(temp) { printf("%d",temp->info); temp=temp->link; } } void main() { void insert(); int del(); void display(); int i,j,k; char ch; start.link=NULL; do { printf("\n1.Insert :"); printf("\n2.Delete :"); printf("\n3.Display :"); printf("\n4.Exit :"); printf("\nEnter your Choice :"); scanf("%d",&i); switch(i) { case 1:insert(); display(); break; case 2:j=del(); printf("Item deleted is %d\n",j); display(); break; case 3:display(); break; case 4:exit(0); default:printf("Wrong choice : "); } fflush(stdin); printf("\nAny more :Type y/n :"); scanf("%c",&ch); }while(ch=='y'); getch(); }