Java Program to Implement LinkedList

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to implement LinkedList

class LinkedList {

  // create an object of Node class
  // represent the head of the linked list
  Node head;

  // static inner class
  static class Node {
    int value;

    // connect each node to next node
    Node next;

    Node(int d) {
      value = d;
      next = null;
    }
  }

  public static void main(String[] args) {

    // create an object of LinkedList
    LinkedList linkedList = new LinkedList();

    // assign values to each linked list node
    linkedList.head = new Node(1);
    Node second = new Node(2);
    Node third = new Node(3);

    // connect each node of linked list to next node
    linkedList.head.next = second;
    second.next = third;

    // printing node-value
    System.out.print("LinkedList: ");
    while (linkedList.head != null) {
      System.out.print(linkedList.head.value + " ");
      linkedList.head = linkedList.head.next;
    }
  }
}

Output

LinkedList: 1 2 3 

In the above example, we have implemented the singly linked list in Java. Here, the linked list consists of 3 nodes.

Each node consists of value and next. The value variable represents the value of the node and the next represents the link to the next node.

To learn about the working of LinkedList, visit LinkedList Data Structure.


Example 2: Implement LinkedList using LinkedList class

Java provides a built LinkedList class that can be used to implement a linked list.

import java.util.LinkedList;

class Main {
  public static void main(String[] args){

    // create a linked list using the LinkedList class
    LinkedList<String> animals = new LinkedList<>();

    // Add elements to LinkedList
    animals.add("Dog");

    // add element at the beginning of linked list
    animals.addFirst("Cat");

    // add element at the end of linked list
    animals.addLast("Horse");
    System.out.println("LinkedList: " + animals);

    // access first element
    System.out.println("First Element: " + animals.getFirst());

    // access last element
    System.out.println("Last Element: " + animals.getLast());
    }
}

Output

LinkedList: [Cat, Dog, Horse]
First Element: Cat 
Last Element: Horse

In the above example, we have used the LinkedList class to implement the linked list in Java. Here, we have used methods provided by the class to add elements and access elements from the linked list.

Notice, we have used the angle brackets (<>) while creating the linked list. It represents that the linked list is of the generic type.

Did you find this article helpful?