Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Implementing a Linked List in Java using Class

Last Updated on July 2, 2024 by Abhishek Sharma

Linked lists are fundamental data structures in computer science, providing a dynamic and flexible way to store and manage a collection of elements. Unlike arrays, linked lists do not require a contiguous block of memory, allowing for efficient insertions and deletions. In Java, implementing a linked list using classes involves creating a series of nodes, where each node contains data and a reference to the next node in the sequence. This approach not only helps in understanding the underlying mechanics of data structures but also enhances problem-solving skills by providing a hands-on experience with dynamic memory management.

Linked List Creation

Structure of a node:
Each linked list node consists of 2 parts:

  • Data: The Data which is stored at a particular address.
  • Reference: Contains the address of the next node of the linked list.

Creating class Node:

class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

A linked List can be created by linking together the nodes.

  • The first node of the list is called a head, and the last node of the list is called a tail.
  • Each and every node in the list can be accessed by traversing through the list from head to tail.

In this article, we will be explaining how to add a new node in the linked list at the end or at any specified position. We will also explain how to delete any existing node in the Linked List.

Insertion Operations

Inserting at the end of the linked list

In this, we will insert a new node at the end of the Linked List.

For example, if we have a Linked List 2→4→6→8→10, and we want to insert 12 at the end of the linked list.

  • After inserting 12 at the end of the given linked list, our updated linked list will be: 2→4→6→8→10→12.

Algorithm To Create Linked List In Java Using Class

  • As a Linked List is represented by the head pointer, so to insert a new node at the end of the linked list, we will use another pointer tail which will always point to the last node of the list.
  • First, we will create a new node to be inserted, let’s say new_node, with given data.
  • Then we will check if the head is null or not.
    • If the head is null, then make:
    • head = new_node
    • tail = new_node
    • Else, if the head is not null, then make:
    • tail.next = new_node
    • tail = new_node

Code Implementation To Create Linked List In Java Using Class

public class InsertNode {
    // Linked list node structure
    class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    public Node head = null;
    public Node tail = null;

    // addNode() it will add a new node at the end of the linked list
    public void addNode(int data) {
        // Creating a new node
        System.out.println("Adding a new node with value "+data+" at the end of the linked list ");
        Node new_Node = new Node(data);

        // it will check if the list is empty or not
        if (head == null) {
            // when list is empty,head and tail point to new node
            head = new_Node;
            tail = new_Node;
        } else {
            // new_Node will be added after tail such that tail's next will point to newNode
            tail.next = new_Node;
            // new_Node will become new tail of the list
            tail = new_Node;
        }
    }

    // PrintData() will display all the nodes present in the list
    public void PrintData() {

        Node current = head;
        if (head == null) {
            System.out.println("Linked List is empty");
            return;
        }
        while (current != null) {
            // It will print each node by incrementing pointer
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {

        InsertNode List = new InsertNode();

        // Add 5 to the end of the list
        List.addNode(5);
        List.PrintData();

        // Add 4 to the end of the list
        List.addNode(4);
        List.PrintData();

        // Add 3 to the end of the list
        List.addNode(3);
        List.PrintData();

        // Add 2 to the end of the list
        List.addNode(2);
        List.PrintData();
    }
}

Output
Adding a new node with value 5 at the end of the linked list
5
Adding a new node with value 4 at the end of the linked list
5 4
Adding a new node with value 3 at the end of the linked list
5 4 3
Adding a new node with value 2 at the end of the linked list
5 4 3 2

Inserting at specific position in the linked list

In this method, we will traverse up to n elements, where n is equal to given position and add the node at that position.

For example, if we have a Linked List 1→2→3→4, and we want to insert a node with data = 5 at the 2nd position in the linked list.

  • After inserting a new node with data = 5 at 2nd position in our linked list, our resultant linked list will look like: 1→2→5→3→4.
  • Note: Take 0 based indexing while finding positions.

Algorithm To Create Linked List In Java Using Class

  • If the position is equal to 1, add the new_node before the head node.
    • new_node.nextNode = headNode;
    • head = new_node;
  • Otherwise, iterate up to the specified position using headNode and then do the following steps:
    • new_node.nextNode = headNode.nextNode;
    • headNode.nextNode = new_node;

Note: Variables names in the algorithm are the same as that in code, so for better understanding, go through code and algorithm at the same time.

Code Implementation To Create Linked List In Java Using Class

public class InsertNode {
    // Linked list node structure
    static class Node {
        public int data;
        public Node nextNode;

        // Constructor
        public Node(int data) {
            this.data = data;

        }
    }

    // Method to insert a node at position pos.
    static Node Insert(Node headNode, int pos, int data) {
        Node head = headNode;
        if (pos < 1)
            System.out.print("Invalid pos");

        if (pos == 1) {
            Node new_node = new Node(data);
            new_node.nextNode = headNode;
            head = new_node;
        } else {
            while (pos-- != 0) {
                if (pos == 1) {

                    Node new_node = new Node(data);

                    new_node.nextNode = headNode.nextNode;
                    headNode.nextNode = new_node;
                    break;
                }
                headNode = headNode.nextNode;
            }
            if (pos != 1)
                System.out.print("Position out of bound");
        }
        return head;
    }
    // PrintData() will display all the nodes present in the list
    static void PrintData(Node node) {
        while (node != null) {
            System.out.print(node.data);
            node = node.nextNode;
            if (node != null)
                System.out.print("->");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.nextNode = new Node(2);
        head.nextNode.nextNode = new Node(3);
        head.nextNode.nextNode.nextNode = new Node(4);

        System.out.print("Original Linked List: ");
        PrintData(head);

        // Insert a node at any position
        int data = 24, pos = 5;
        head = Insert(head, pos, data);
        System.out.print("Linked list after adding a node with data "+data+" at position "+pos+": ");
        PrintData(head);

        // Inserting a node at first position
        data = 39;
        pos = 1;
        head = Insert(head, pos, data);
        System.out.print("Linked list after adding a node with data "+data+" at position "+pos+": ");
        PrintData(head);

        data = 18;
        pos = 7;
        head = Insert(head, pos, data);
        System.out.print("Linked list after adding a node with data "+data+" at position "+pos+": ");
        PrintData(head);
    }
}

Output
Original Linked List: 1->2->3->4
Linked list after adding a node with data 24 at position 5: 1->2->3->4->24
Linked list after adding a node with data 39 at position 1: 39->1->2->3->4->24
Linked list after adding a node with data 18 at position 7: 39->1->2->3->4->24->18

Deletion Operations

In this section, we will see how to delete the first occurrence of the specified node from the linked list, i.e., deleting the first occurrence of a given key from the linked list.

For example, if we have a Linked List 2→4→6→4→10, and we want to delete the first occurrence of node with value 4 (key = 4) from the linked list.

  • After deleting the first occurrence of node with value 4 from the linked list, our resultant linked list will be: 2→6→4→10.

Algorithm To Create Linked List In Java Using Class

  • Condition1: If the key is at the head.

    • Change the head node to the next node of the current head.
    • list.head = current_Node.next;
  • Condition 2: The key is either in the middle or last, except at the head.

    • In this condition, find the previous node of the node to be deleted.

    • prev = current_Node;

    • current_Node = current_Node.next;

    • Make the previous node of the node to be deleted point to the next node of the current node.

    • prev.next = current_Node.next;

  • Condition 3: The key is not in the list.

    • Print key not found.

Note: Variables names in the algorithm are the same as that in code, so for better understanding, go through code and algorithm at the same time.

Code Implementation To Create Linked List In Java Using Class

public class LinkedList {

    Node head;
    // Linked list node structure
    static class Node {

        int data;
        Node next;

        // Constructor
        Node(int d)
        {
            data = d;
            next = null;
        }
    }

    public static LinkedList value(LinkedList list, int data)
    {
        
        Node new_node = new Node(data);
        new_node.next = null;

        if (list.head == null) {
            list.head = new_node;
        }
        else {
            Node last = list.head;
            while (last.next != null) {
                last = last.next;
            }

            last.next = new_node;
        }

        return list;
    }

    public static void printData(LinkedList list)
    {
        Node current_Node = list.head;
    
        System.out.print("Linked List :- ");

        while (current_Node != null) {
            System.out.print(current_Node.data + " ");
            current_Node = current_Node.next;
        }
        System.out.println();
    }
 
    // Method to delete the node with data equal to specified key
    public static LinkedList deleteNode(LinkedList list,int key)
    {
        
        Node current_Node = list.head, prev = null;
 
        // Condition 1: Key is  at head
        if (current_Node != null && current_Node.data == key) {
            list.head = current_Node.next;
            System.out.println(key + " is found and deleted");

            return list;
        }
        
        // Condition 2
        while (current_Node != null && current_Node.data != key) {
            prev = current_Node;
            current_Node = current_Node.next;
        }

        if (current_Node != null) {
            prev.next = current_Node.next;
            System.out.println(key + " is found and deleted");
        }
 
        // Condition 3: The key is not  in the list
        if (current_Node == null) {
            System.out.println(key + " not found");
        }

        return list;
    }
 
    
    // Driver code
    public static void main(String[] args)
    {
        LinkedList list = new LinkedList();
        
        list = value(list, 2);
        list = value(list, 6);
        list = value(list, 1);
        list = value(list, 8);
        list = value(list, 9);
        list = value(list, 0);
        list = value(list, 3);
        list = value(list, 5);

        printData(list);
        deleteNode(list, 2);
        printData(list);

        deleteNode(list, 8);
        printData(list);

        deleteNode(list, 20);
        printData(list);
    }
}

Output
Linked List :- 2 6 1 8 9 0 3 5
2 is found and deleted
Linked List :- 6 1 8 9 0 3 5
8 is found and deleted
Linked List :- 6 1 9 0 3 5
20 not found
Linked List :- 6 1 9 0 3 5

**Conclusion**
Implementing a linked list in Java using classes offers a deep dive into one of the most important data structures in computer science. By understanding how nodes are created, linked, and managed, developers gain valuable insights into dynamic memory allocation and data organization. Linked lists are versatile and form the foundation for more complex data structures like stacks, queues, and graphs. Mastering linked list implementation enhances a programmer’s ability to solve a wide range of computational problems efficiently.

## FAQs Related to Implementing a Linked List in Java using Class
Here are some of the FAQs related to Implementing a Linked List in Java using Class:

**Q1: What is a linked list?**
A linked list is a linear data structure where elements are stored in nodes, and each node contains data and a reference (or link) to the next node in the sequence. Unlike arrays, linked lists do not require a contiguous block of memory, making them more flexible for dynamic memory allocation.

**Q2: What are the types of linked lists?**
There are several types of linked lists:

– **Singly Linked List:** Each node points to the next node, and the last node points to null.
– **Doubly Linked List:** Each node has two references, one to the next node and one to the previous node.
– **Circular Linked List:** The last node points back to the first node, forming a circle.

**Q3: What are the advantages of using a linked list over an array?**
The advantages of using a linked list over an array include:

– **Dynamic Size:** Linked lists can grow and shrink in size dynamically, while arrays have a fixed size.
– **Efficient Insertions/Deletions:** Insertions and deletions are more efficient in linked lists, especially for large data sets, because they do not require shifting elements as arrays do.

**Q4: What are the disadvantages of using a linked list?**
The disadvantages of using a linked list include:

– **Memory Overhead:** Linked lists require extra memory for storing references to the next (and previous, in doubly linked lists) nodes.
– **Sequential Access:** Linked lists do not support efficient random access to elements, unlike arrays, which offer constant-time access based on index.

**Q5: How can linked lists be used in real-world applications?**
Linked lists are used in various real-world applications, such as:

– **Dynamic Memory Allocation:** Used in operating systems for managing free memory.
– **Implementing Data Structures:** Used to implement other data structures like stacks, queues, and graphs.
– **Navigating Previous and Next:** Used in applications like web browsers for back and forward navigation.

Leave a Reply

Your email address will not be published. Required fields are marked *