Skip to main content

Command Palette

Search for a command to run...

Mastering Data Structures : A Comprehensive Guide to Efficient Coding

Published
10 min read
S

🌐 Tech Enthusiast | Curious Learner | Knowledge Sharer Hello! Currently, I am pursuing a Master's degree in Computer Applications (MCA) from the Heritage Institute of Technology. Since the world of technology is dynamic, I posted some pieces based on my experiences and what is trending right now. My blog is an informative space where it is possible to create a community, learn together, and grow. Considering my interests in Web Development, Artificial Intelligence, and DevOps, I am always ready to explore new technologies, share knowledge with others, and step up the ladder of success simultaneously. Join me as I navigate this exciting journey of growth and innovation! 🚀

Topics: - [Array]- [ Linked List] -[Singly linked list]

Array

An array is a collection of similar types of data stored at contiguous memory locations. It is the simplest data structure where each data element can be accessed directly by only using its index number.

For instance, if we want to store the marks scored by a student in 5 subjects, then there’s no need to define individual variables for each subject. Rather, we can define an array that will store the data elements at contiguous memory locations.

Array marks[5] define the marks scored by a student in 5 different subjects where each subject’s marks are located at a particular location in the array, i.e., marks[0] denote the marks scored in the first subject, marks[1] denotes the marks scored in 2nd subject and so on.

Why we need Array?

In programming, most of the cases need to store a large amount of data of a similar type. We need to define numerous variables to store such a huge amount of data. While writing the programs, it would be very tough to memorize all variable names. Instead, it is better to define an array and store all the elements in it.

The following example illustrates how an array can be used while writing a code-

In the following example, we have given marks to a student in 5 different subjects. The aim is to calculate the average of a student’s marks.

Without Using Array

#include <stdio.h>
int main() { // Declare individual variables for marks int mark1 = 85; int mark2 = 90; int mark3 = 78; int mark4 = 88; int mark5 = 92;
int sum; float average;
// Calculate the sum of marks 
sum = mark1 + mark2 + mark3 + mark4 + mark5;
// Calculate the average 
average = sum / 5.0;
// Print the average 
printf("Average marks: %.2f\n", average);
return 0; }

Using Array

#include <stdio.h>
int main() { // Declare an array to store marks 
int marks[5];
 int sum = 0;
 float average;
// Initialize the array with marks 
marks[0] = 85; marks[1] = 90; marks[2] = 78; marks[3] = 88; marks[4] = 92;
// Calculate the sum of marks 
for (int i = 0; i < 5; i++) { sum += marks[i]; }
// Calculate the average 
average = sum / 5.0;
// Print the average 
printf("Average marks: %.2f\n", average);
return 0; }

The Complexity of Array Operations

Time Complexity

AlgorithmAverage caseWorst case
AccessO(1)O(1)
SearchO(n)O(n)
InsertionO(n)O(n)
DeletionO(n)O(n)

The space complexity of an array for the worst case is O(n).

Advantages of Array

  • Arrays represent multiple data elements of the same type using a single name.

  • Accessing or searching an element in an array is easy by using the index number.

  • An array can be traversed easily just by incrementing the index by 1.

  • Arrays allocate memory in contiguous memory locations for all its data elements.

Types of indexing in Array

· 0 (Zero Based Indexing)- The first element of the array refers to index 0.

· 1 (One Based Indexing)- The first element of the array refers to index 1.

· n (n Based Indexing)- The base index of an array can be chosen as per requirement.

Linked List

  • Linked List can be defined as collection of objects called nodes that are randomly stored in the memory.

  • A node contains two fields i.e. data stored at that particular address and the pointer which contains the address of the next node in the memory.

  • The last node of the list contains pointer to the null.

DS Linked List

Uses of Linked List

  • The list is not required to be contiguously present in the memory. The node can reside any where in the memory and linked together to make a list. This achieves optimized utilization of space.

  • list size is limited to the memory size and doesn't need to be declared in advance.

  • Empty node can not be present in the linked list.

  • We can store values of primitive types or objects in the singly linked list.

Why use linked list over array?

Till now, we were using array data structure to organize the group of elements that are to be stored individually in the memory. However, Array has several advantages and disadvantages which must be known in order to decide the data structure which will be used throughout the program.

Array contains following limitations:

  1. The size of array must be known in advance before using it in the program.

  2. Increasing size of the array is a time taking process. It is almost impossible to expand the size of the array at run time.

  3. All the elements in the array need to be contiguously stored in the memory. Inserting any element in the array needs shifting of all its predecessors.

Linked list is the data structure which can overcome all the limitations of an array. Using linked list is useful because,

  1. It allocates the memory dynamically. All the nodes of linked list are non-contiguously stored in the memory and linked together with the help of pointers.

  2. Sizing is no longer a problem since we do not need to define its size at the time of declaration. List grows as per the program's demand and limited to the available memory space.

Singly linked list or One way chain

Singly linked list can be defined as the collection of ordered set of elements. The number of elements may vary according to need of the program. A node in the singly linked list consist of two parts: data part and link part. Data part of the node stores actual information that is to be represented by the node while the link part of the node stores the address of its immediate successor.

One way chain or singly linked list can be traversed only in one direction. In other words, we can say that each node contains only next pointer, therefore we can not traverse the list in the reverse direction.

Consider an example where the marks obtained by the student in three subjects are stored in a linked list as shown in the figure.

DS Singly Linked List

In the above figure, the arrow represents the links. The data part of every node contains the marks obtained by the student in the different subject. The last node in the list is identified by the null pointer which is present in the address part of the last node. We can have as many elements we require, in the data part of the list.

Complexity

Data StructureTime ComplexitySpace Complexity
AverageWorst
AccessSearch
Singly Linked Listθ(n)θ(n)

Operations on Singly Linked List

There are various operations which can be performed on singly linked list. A list of all such operations is given below.

Node Creation

struct node{  
    int data;   
    struct node *next;  
};  
struct node head, ptr;   
ptr = (struct node )malloc(sizeof(struct node ));

Insertion

The insertion into a singly linked list can be performed at different positions. Based on the position of the new node being inserted, the insertion is categorized into the following categories.

SNOperationDescription
1Insertion at beginningIt involves inserting any element at the front of the list. We just need to a few link adjustments to make the new node as the head of the list.
2Insertion at end of the listIt involves insertion at the last of the linked list. The new node can be inserted as the only node in the list or it can be inserted as the last one. Different logics are implemented in each scenario.
3Insertion after specified nodeIt involves insertion after the specified node of the linked list. We need to skip the desired number of nodes in order to reach the node after which the new node will be inserted. .

Deletion and Traversing

The Deletion of a node from a singly linked list can be performed at different positions. Based on the position of the node being deleted, the operation is categorized into the following categories.

SNOperationDescription
1Deletion at beginningIt involves deletion of a node from the beginning of the list. This is the simplest operation among all. It just need a few adjustments in the node pointers.
2Deletion at the end of the listIt involves deleting the last node of the list. The list can either be empty or full. Different logic is implemented for the different scenarios.
3Deletion after specified nodeIt involves deleting the node after the specified node in the list. we need to skip the desired number of nodes to reach the node after which the node will be deleted. This requires traversing through the list.
4TraversingIn traversing, we simply visit each node of the list at least once in order to perform some specific operation on it, for example, printing data part of each node present in the list.
5SearchingIn searching, we match each element of the list with the given element. If the element is found on any of the location then location of that element is returned otherwise null is returned. .

ALL singly linked list operations in C

#include<stdio.h>  
#include<stdlib.h>  
struct node   
{  
    int data;  
    struct node *next;   
};  
struct node *head;  

void beginsert ();   
void lastinsert ();  
void randominsert();  
void begin_delete();  
void last_delete();  
void random_delete();  
void display();  
void search();  
void main ()  
{  
    int choice =0;  
    while(choice != 9)   
    {  
        printf("\n\n*********Main Menu*********\n");  
        printf("\nChoose one option from the following list ...\n");  
        printf("\n===============================================\n");  
        printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from Beginning\n  
        5.Delete from last\n6.Delete node after specified location\n7.Search for an element\n8.Show\n9.Exit\n");  
        printf("\nEnter your choice?\n");         
        scanf("\n%d",&choice);  
        switch(choice)  
        {  
            case 1:  
            beginsert();      
            break;  
            case 2:  
            lastinsert();         
            break;  
            case 3:  
            randominsert();       
            break;  
            case 4:  
            begin_delete();       
            break;  
            case 5:  
            last_delete();        
            break;  
            case 6:  
            random_delete();          
            break;  
            case 7:  
            search();         
            break;  
            case 8:  
            display();        
            break;  
            case 9:  
            exit(0);  
            break;  
            default:  
            printf("Please enter valid choice..");  
        }  
    }  
}  
void beginsert()  
{  
    struct node *ptr;  
    int item;  
    ptr = (struct node *) malloc(sizeof(struct node *));  
    if(ptr == NULL)  
    {  
        printf("\nOVERFLOW");  
    }  
    else  
    {  
        printf("\nEnter value\n");    
        scanf("%d",&item);    
        ptr->data = item;  
        ptr->next = head;  
        head = ptr;  
        printf("\nNode inserted");  
    }  

}  
void lastinsert()  
{  
    struct node *ptr,*temp;  
    int item;     
    ptr = (struct node*)malloc(sizeof(struct node));      
    if(ptr == NULL)  
    {  
        printf("\nOVERFLOW");     
    }  
    else  
    {  
        printf("\nEnter value?\n");  
        scanf("%d",&item);  
        ptr->data = item;  
        if(head == NULL)  
        {  
            ptr -> next = NULL;  
            head = ptr;  
            printf("\nNode inserted");  
        }  
        else  
        {  
            temp = head;  
            while (temp -> next != NULL)  
            {  
                temp = temp -> next;  
            }  
            temp->next = ptr;  
            ptr->next = NULL;  
            printf("\nNode inserted");  

        }  
    }  
}  
void randominsert()  
{  
    int i,loc,item;   
    struct node *ptr, *temp;  
    ptr = (struct node *) malloc (sizeof(struct node));  
    if(ptr == NULL)  
    {  
        printf("\nOVERFLOW");  
    }  
    else  
    {  
        printf("\nEnter element value");  
        scanf("%d",&item);  
        ptr->data = item;  
        printf("\nEnter the location after which you want to insert ");  
        scanf("\n%d",&loc);  
        temp=head;  
        for(i=0;i<loc;i++)  
        {  
            temp = temp->next;  
            if(temp == NULL)  
            {  
                printf("\ncan't insert\n");  
                return;  
            }  

        }  
        ptr ->next = temp ->next;   
        temp ->next = ptr;   
        printf("\nNode inserted");  
    }  
}  
void begin_delete()  
{  
    struct node *ptr;  
    if(head == NULL)  
    {  
        printf("\nList is empty\n");  
    }  
    else   
    {  
        ptr = head;  
        head = ptr->next;  
        free(ptr);  
        printf("\nNode deleted from the begining ...\n");  
    }  
}  
void last_delete()  
{  
    struct node *ptr,*ptr1;  
    if(head == NULL)  
    {  
        printf("\nlist is empty");  
    }  
    else if(head -> next == NULL)  
    {  
        head = NULL;  
        free(head);  
        printf("\nOnly node of the list deleted ...\n");  
    }  

    else  
    {  
        ptr = head;   
        while(ptr->next != NULL)  
        {  
            ptr1 = ptr;  
            ptr = ptr ->next;  
        }  
        ptr1->next = NULL;  
        free(ptr);  
        printf("\nDeleted Node from the last ...\n");  
    }     
}  
void random_delete()  
{  
    struct node *ptr,*ptr1;  
    int loc,i;    
    printf("\n Enter the location of the node after which you want to perform deletion \n");  
    scanf("%d",&loc);  
    ptr=head;  
    for(i=0;i<loc;i++)  
    {  
        ptr1 = ptr;       
        ptr = ptr->next;  

        if(ptr == NULL)  
        {  
            printf("\nCan't delete");  
            return;  
        }  
    }  
    ptr1 ->next = ptr ->next;  
    free(ptr);  
    printf("\nDeleted node %d ",loc+1);  
}  
void search()  
{  
    struct node *ptr;  
    int item,i=0,flag;  
    ptr = head;   
    if(ptr == NULL)  
    {  
        printf("\nEmpty List\n");  
    }  
    else  
    {   
        printf("\nEnter item which you want to search?\n");   
        scanf("%d",&item);  
        while (ptr!=NULL)  
        {  
            if(ptr->data == item)  
            {  
                printf("item found at location %d ",i+1);  
                flag=0;  
            }   
            else  
            {  
                flag=1;  
            }  
            i++;  
            ptr = ptr -> next;  
        }  
        if(flag==1)  
        {  
            printf("Item not found\n");  
        }  
    }     

}  

void display()  
{  
    struct node *ptr;  
    ptr = head;   
    if(ptr == NULL)  
    {  
        printf("Nothing to print");  
    }  
    else  
    {  
        printf("\nprinting values . . . . .\n");   
        while (ptr!=NULL)  
        {  
            printf("\n%d",ptr->data);  
            ptr = ptr -> next;  
        }  
    }  
}

More from this blog

Hoisting in JavaScript

9 posts