How to implement a linked list in Java

  • Post author:
  • Post category:java
  • Post comments:0 Comments

What is Linked List

A linked list is a data structure that is used to store a sequence of elements, where each element is represented by a node that contains a value and a reference to the next node in the list. In this tutorial, we will show you how to implement a linked list in Java.

  1. First, you will need to create a Node class that represents a single element in the list. The class should have a value field and a next field, which is a reference to the next node in the list.
class Node {
    int value;
    Node next;
    public Node(int value) {
        this.value = value;
    }
}
  1. Next, you will need to create a LinkedList class that will hold the nodes. The class should have a head field, which is a reference to the first node in the list.
class LinkedList {
    Node head;
}
  1. Now you can implement the add() method that takes in a value and adds a new node to the list. The new node should be added at the head of the list, and the head field should be updated to reference the new node.
void add(int value) {
    Node newNode = new Node(value);
    newNode.next = head;
    head = newNode;
}
  1. Similarly, you can implement the remove() method that takes in a value and removes the corresponding node from the list. The method should iterate through the list and update the next field of the previous node to skip over the node to be removed.
void remove(int value) {
    Node current = head;
    if (current != null && current.value == value) {
        head = current.next;
        return;
    }

    while (current != null && current.next != null) {
        if (current.next.value == value) {
            current.next = current.next.next;
            return;
        }
        current = current.next;
    }
}
  1. Finally, you can implement the print() method that prints the values of all the nodes in the list. The method should iterate through the list and print the value of each node.
void print() {
    Node current = head;
    while (current != null) {
        System.out.print(current.value + " ");
        current = current.next;
    }
    System.out.println();
}

It is important to note that this is a basic implementation of the linked list and there are many variations and optimizations that can be made depending on the specific use case. Additionally, this example uses a singly linked list, but you can also implement doubly linked list as well.

Leave a Reply