1. Home
Data Structure

Data Structure Tutorial: Everything You Need to Know

Learn all about data structures with our comprehensive tutorial. Master the fundamentals and advance your skills in organizing and managing data efficiently.

  • 60
  • 14
right-top-arrow

Tutorial Playlist

58 Lessons
54

Mastering Linked Lists in Data Structure: Types, Applications, and Implementation Guide

Updated on 23/08/2024432 Views

Introduction to Linked List in Data Structure

A linked list is a fundamental data structure that stores elements in a linear order. Unlike arrays, a linked list in data structure stores elements in nodes that link to the next element. It offers dynamic memory allocation and flexibility in data management. Imagine a chain where each link connects to the next; that's how linked lists function. They are helpful in situations where the size of the data set changes over time. This tutorial will walk you through the basics and show why linked lists are important in programming.

Overview Of Linked List in Data Structure

The many forms of linked lists in data structure serve different needs. The simplest form is the singly linked list. It contains nodes that point to the next node in the sequence. For complex linking, doubly linked lists allow navigation both forward and backward. The other one, Circularly linked lists, forms a loop and connects the last node back to the first, which is great for circular queues or buffering.

Thus, we will explore these types, talk about the creation of programs for linked lists in languages like C and Java, and discuss their applications. By the end of this tutorial, you will have a solid grasp of how to implement and use linked lists in your projects and enhance your data management skills.

Understanding Types of Linked List in Data Structure

Types of Linked List
The different forms of the linked lists, which serve different programming needs, are a crucial part of the data structures.

Singly Linked List

  • In a singly linked list, each node points to the next node in the sequence, allowing for one-way traversal.
  • Example Use: Consider a simple to-do list application. Here, you can add tasks (nodes) one after the other to create a chain of tasks. A singly linked list lets you move from start to end, viewing each task in order.

Code

typedef struct Node {

    int data;

    struct Node* next;

} Node;

Doubly Linked List

  • The doubly linked lists in data structure link to both the next and previous nodes. They enable two-way traversal.
  • Example Use: In an eBook reader, you might want to navigate pages forward and backward. A doubly linked list perfectly models this, where each page is a node with links to both the previous and next pages.

Code

class Node {

    int data;

    Node prev;

    Node next;

}

Circular Singly Linked List

  • This variant has the last node that points back to the first node, and forms a loop. It's a singly linked list that wraps around.
  • Example Use: A great example is a multiplayer game where turns rotate among players. Once the last player takes a turn, it loops back to the first player, mirroring a circular singly linked list's structure.

Code

typedef struct Node {

    int data;

    struct Node* next;

} Node;

Results: The next pointer of the last node would be set to the head of the list.

Circular Doubly Linked List

  • Combining the features of doubly linked and circular lists, this type supports endless bidirectional traversal.
  • Example Use: Imagine a playlist that plays on repeat. You can skip forward from the last song to the first or go back from the first song to the last. A circular doubly linked list can mimic this behavior.

Code

class Node {

    int data;

    Node prev;

    Node next;

}

Result: The last node's next would point to the head, and the head's previous would point to the last node.

Building a Program for Singly Linked List in Data Structure In C

A basic understanding of the language is required before the creation of a singly linked list in data structure program in C language. You need to know about the basics of nodes, pointers, and dynamic memory allocation. However, if you are a complete beginner, you can follow these steps to build your program.

Let's build a simple program step by step and focus on key operations such as the creation of a list, insertion of nodes, and display of the list.

Step 1: Define the Node Structure

First, we need to define what a node is. The nodes store an integer value and a pointer to the next node.

Code

#include <stdio.h>

#include <stdlib.h>

// A structure to represent a node

typedef struct Node {

    int data;

    struct Node* next;

} Node;

Step 2: Inserting Nodes

We will write a function that creates a new node with a given value and appends it to the end of the list, to insert nodes into our singly linked list.

Code

// Function to insert a node at the end of the list

void insertEnd(Node** head, int newData) {

    // Create a new node and allocate memory

    Node* newNode = (Node*) malloc(sizeof(Node));

    Node* last = *head; // Used to traverse the list

    newNode->data = newData; // Assign data to the new node

    newNode->next = NULL; // The new node is going to be the last node, so make its next NULL

// If the list is empty, then make the new node as head

    if (*head == NULL) {

        *head = newNode;

        return;

    }

// Else traverse till the last node

    while (last->next != NULL) {

        last = last->next;

    }

// Change the next of the last node

    last->next = newNode;

}

Step 3: Displaying the List

We will iterate through each node and print its value until we reach the end of the list to display it.

Code

// Function to print the linked list

void printList(Node* node) {

    while (node != NULL) {

        printf("%d -> ", node->data);

        node = node->next;

    }

    printf("NULL\n");

}

Step 4: Main Function

Now, let's use our functions in the main function to create a list, insert some values, and display them.

Code

int main() {

    Node* head = NULL; // Start with an empty list


    insertEnd(&head, 1);

    insertEnd(&head, 2);

    insertEnd(&head, 3);

    insertEnd(&head, 4);


    printf("Created Linked List: ");

    printList(head);


    return 0;

}

Final Output

Created Linked List: 1 -> 2 -> 3 -> 4 -> NULL

Implementing Linked List in Data Structure Using Java

Linked List in Data Structure Using Java

The implementation of a linked list in Java involves the creation of a custom class for the nodes of the list and another class for the linked list itself. Here's a basic example of how to create a singly linked list in data structure with operations to add, print, and delete nodes. This will give you a basic understanding of how to work with linked lists in Java.

Node Class

First, we define a Node class, which will represent each element in the list. This class has two parts: the data you want to store and a reference to the next node.

Code

class Node {

    int data;

    Node next;


    // Constructor to create a new node

    // Next is by default initialized as null

    Node(int d) {

        data = d;

        next = null;

    }

}

Linked List Class

Next, we create a LinkedList class to manage the nodes. This class will have a head reference point at the start of the list and functions to add, delete, and display nodes.

public class LinkedList {

    Node head; // head of the list


    // Method to insert a new node

    public void insert(int data) {

        // Create a new node with given data

        Node newNode = new Node(data);

        newNode.next = null;


        // If the Linked List is empty, then make the new node as head

        if (head == null) {

            head = newNode;

        } else {

            // Else traverse till the last node and insert the new_node there

            Node last = head;

            while (last.next != null) {

                last = last.next;

            }


            // Insert the new_node at last node

            last.next = newNode;

        }

    }


    // Method to print the LinkedList.

    public void printList() {

        Node currentNode = head;

        System.out.print("LinkedList: ");

        // Traverse through the LinkedList

        while (currentNode != null) {

            // Print the data at current node

            System.out.print(currentNode.data + " ");

            // Go to next node

            currentNode = currentNode.next;

        }

        System.out.println();

    }


    // Method to delete a node in the LinkedList by KEY

    public void deleteByKey(int key) {

        // Store head node

        Node temp = head, prev = null;


        // If head node itself holds the key to be deleted

        if (temp != null && temp.data == key) {

            head = temp.next; // Changed head

            return;

        }


        // Search for the key to be deleted, keep track of the previous node as we need to change temp.next

        while (temp != null && temp.data != key) {

            prev = temp;

            temp = temp.next;

        }


        // If key was not present in linked list

        if (temp == null) return;


        // Unlink the node from linked list

        prev.next = temp.next;

    }

}

Testing the Linked List

Finally, you can test the linked list in data structure by the creation of a LinkedList object, using its methods to manipulate the list.

public class Main {iterate

    public static void main(String[] args) {

        LinkedList list = new LinkedList();


        list.insert(1);

        list.insert(2);

        list.insert(3);

        list.insert(4);


        System.out.println("Created linked list is: ");

        list.printList();


        list.deleteByKey(3); // Delete node with data 3


        System.out.println("Linked List after Deletion of 3:");

        list.printList();

    }

}

This example shows the basics of how to implement a linked list in Java. You can also add more functionalities, like the insertion of a specific index, reversing the list, or search elements.

Creating a Circular Linked List in Data Structure Program

Circular Linked List

The creation of a circular linked list in data structure involves setting up a linked list where the last node points back to the first node, which further creates a loop. This setup is useful for applications that require cyclic traversals, like a round-robin scheduler or a carousel menu. Let's learn how to create a circular linked list with a simple example program.

We will build a basic circular linked list where each node contains an integer value. We will implement methods to add new nodes to the list and display the list contents.

Code

class Node {

    int data;

    Node next;


    public Node(int data) {

        this.data = data;

        this.next = null;

    }

}


class CircularLinkedList {

    Node head = null;

    Node tail = null;


    // Method to add a new node

    public void add(int data) {

        Node newNode = new Node(data);

        if (head == null) {

            head = newNode;

            tail = newNode;

            newNode.next = head;

        } else {

            tail.next = newNode;

            tail = newNode;

            tail.next = head;

        }

    }


    // Method to display the list

    public void display() {

        Node current = head;

        if(head != null) {

            do {

                System.out.print(current.data + " ");

                current = current.next;

            } while(current != head);

        }

        System.out.println();

    }

}


public class Main {

    public static void main(String[] args) {

        CircularLinkedList clist = new CircularLinkedList();

        

        // Adding data to the list

        clist.add(1);

        clist.add(2);

        clist.add(3);

        clist.add(4);


        // Displaying the circular linked list

        System.out.println("Circular Linked List: ");

        clist.display();

    }

}

Key Points in the Program:

  • Node Class: This class represents each element or node in the list, which holds data and a reference to the next node.
  • CircularLinkedList Class: It manages the circular linked list operations, including the addition of new nodes and display of the list.
  • Add Method: It inserts new nodes into the list. If the list is empty, it sets the new node as the head and tail. It also points to itself after the creation of a single-node loop. Otherwise, it adds the new node at the end, updates the tail's next reference to point to the head, and maintains the circular structure.
  • Display Method: It traverses the list that starts from the head and prints out  the data of all nodes until it reaches the head again. This indicates the list's circular nature.

Advanced Applications of Linked List in Data Structure

Linked lists in data structure, with their flexibility, have many uses. Let's see some of the advanced applications of these structures. 

1. Memory Management

  • Operating systems use linked lists for memory management. They dynamically allocate memory and keep track of used and free memory blocks. Linked lists are efficient for this task because of their easy adjustment to varying block sizes without the need for continuous memory space.
  • Example: Free memory blocks might be tracked by the use of a linked list. When a program requests memory, the system can traverse this list to find a large block and adjust the linked list to reflect memory allocation.

2. Undo Functionality in Applications

  • Many applications, like word processors and graphic design software, implement undo functionality by the use of linked lists. Each node in the list can represent the state of the document or artwork. When the user performs an action, a new state is added to the list.
  • Example: In a text editor, each node represents the text content after each change. To undo, the application can revert to the previous node's state, effectively rolling back to the last action.

3. Blockchain Implementation

  • A blockchain is a specialized form of linked list, where each block (node) contains data and a hash of the previous block to create a secure chain.
  • Example: Cryptocurrencies, like Bitcoin, use blockchain technology to maintain a secure and decentralized ledger of transactions. Each transaction block links to the previous one and ensures data integrity through cryptographic hashes.

4. Circular Buffers

  • Circular linked lists are well-suited for the implementation of circular buffers. They are used when data overwrites itself after reaching the buffer's capacity. This is common in streaming applications.
  • Example: In multimedia applications, a circular buffer is used to manage audio streams. When the buffer fills up, new audio data overwrites the oldest data and lets data process continuously.

5. Graph Representation

  • Graphs can be represented by the use of linked lists. Each node represents a graph vertex and each link represents an edge. This is useful for sparse graphs.
  • Example: In a transportation network, each station could be a node, and each route between stations could be a link. This structure helps navigation and route planning algorithms.

6. Sparse Matrices

  • Linked lists are effective in storing sparse matrices where elements are zero. Linked lists store only the non-zero elements and their positions instead of wasting space for zeros.
  • Example: In scientific computing, large sparse matrices represent physical systems. The use of linked lists conserves memory and increases computational efficiency when manipulating these matrices.

Final Words

Linked lists in data structure are a fundamental structure. They are used in several applications across computing and information technology. Their adaptability to dynamic data management scenarios—from simple lists to complex graph representations—makes them an invaluable tool in the programmer's toolkit. Linked lists offer the flexibility and efficiency needed to manage challenges like memory management schemes, blockchain technologies, undo functionalities in applications, circular buffers, and sparse matrices.

FAQs

  1. What are the 4 types of linked lists?

The four types of linked lists are

  • Singly linked lists
  • Doubly linked lists
  • Circular singly linked lists
  • Circular doubly linked lists.
  1. What is an example of a linked list?

An example of a linked list would be a playlist, where each song (node) contains information about the song and a pointer to the next song in the list.

  1. What is the syntax of a linked list in C?

The syntax to create a linked list node in C would be

struct Node {

    int data;

    struct Node* next;

};

  1. What is a linked list as an ADT?

A linked list as an Abstract Data Type (ADT) is a collection of items where each item points to the next. It allows dynamic data organization, insertion, and deletion without fixed memory size.

  1. What are linked lists used for?

Linked lists are used for efficient data management when the size of the dataset changes dynamically. They are suitable for implementing queues, stacks, graphs, and other dynamic data structures.

  1. What is a linked list class?

A linked list class in object-oriented programming languages like Java or C++ encapsulates the properties (data elements) and behaviors (functions or methods) needed to implement a linked list's functionality.

  1. What is a simple linked list?

A simple (or singly) linked list is a data structure where each element (node) contains data and a reference (or pointer) to the next node in the sequence, which further forms a linear collection.

  1. Why is a linked list the best?

Linked lists are best for situations that need flexible memory allocation, efficient insertions, and deletions, and when the data size changes dynamically, as they don't require continuous memory space.

Mukesh Kumar

Mukesh Kumar

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...