Create LinkedList in Java

In this blog post, we will learn to create a LinkedList in Java. There are two types of LinkedList.

  • Singly Linked List
  • Doubly Linked List

Singly Linked List

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

class LinkedList {
    Node head;
    public void add(int data) {
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }
    public void print() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.print();
    }
}

This code creates a singly linked list with three nodes containing the values 1, 2, and 3. The add() method adds a new node to the head of the list, and the print() method prints the values of the nodes in the list.

The output of this code will be:

3 2 1

It’s worth noting that in addition to the singly linked list, there is also a doubly linked list in Java. The only difference between the two is that, in the doubly linked list, each node has a reference to the previous node as well as the next one.

Doubly Linked List

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

class DoublyLinkedList {
    Node head;
    Node tail;
    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            tail = newNode;
        } else {
            newNode.prev = tail;
            tail.next = newNode;
            tail = newNode;
        }
    }
    public void print() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        DoublyLinkedList list = new DoublyLinkedList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.print();
    }
}

This code creates a doubly linked list with three nodes containing the values 1, 2, and 3. The add() method adds a new node to the tail of the list. In this method, the newNode.prev is assigned to the current tail, and the tail.next is assigned to the newNode, and tail is assigned to the newNode. The print() method prints the values of the nodes in the list starting from the head.

The output of this code will be:

1 2 3

You can visit the difference between Singly Linked List and Double Linked List in our next post to understand it clearly.