Java LinkedList


In Java, a LinkedList is another commonly used data structure that belongs to the Java Collections Framework. It is part of the java.util package and implements both the List and Deque interfaces. Unlike an ArrayList, which uses a dynamic array internally, a LinkedList uses nodes that are linked together. Each node contains two parts — the data and a reference (link) to the next node in the list.

A LinkedList provides better performance than an ArrayList when you frequently add or remove elements from the middle of the list. However, it is slightly slower for accessing elements directly because it has to traverse through the nodes.

What is a LinkedList in Java

A LinkedList is a linear data structure where elements, also called nodes, are connected by links. Each node stores its value and a reference to the next (and sometimes previous) node. Java provides a built-in LinkedList class that can store elements of any type — objects, strings, integers, etc.

The LinkedList class implements both the List and Deque interfaces, meaning it can function as a list, queue, or stack. This makes it a versatile choice for various real-world scenarios.

Syntax of LinkedList

Before using a LinkedList, you must import it from the java.util package.

import java.util.LinkedList;

public class Example {
    public static void main(String[] args) {
        LinkedList<String> names = new LinkedList<String>();
        names.add("Aisha");
        names.add("Meera");
        names.add("Priya");
        System.out.println(names);
    }
}

This program creates a LinkedList of strings and adds three names to it.

Features of LinkedList

  • Stores elements in a sequential order using linked nodes.

  • Allows duplicate and null values.

  • Can function as a list, queue, or stack.

  • Provides faster insertion and deletion in the middle of the list.

  • Slower for random access compared to ArrayList.

  • Maintains insertion order.

Adding Elements to a LinkedList

You can add elements to a LinkedList using the add() method. There are several variations for adding elements at different positions.

LinkedList<Integer> numbers = new LinkedList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.addFirst(5);   // adds element at the beginning
numbers.addLast(40);   // adds element at the end
System.out.println(numbers);

The output will show the list as [5, 10, 20, 30, 40].

Accessing Elements in a LinkedList

You can access elements by index using the get() method.

String first = names.get(0);
System.out.println("First element: " + first);

Additionally, there are special methods like getFirst() and getLast() to access the first and last elements.

System.out.println(names.getFirst());
System.out.println(names.getLast());

Updating Elements in a LinkedList

To modify an existing element, use the set() method.

names.set(1, "Riya");
System.out.println(names);

This replaces the element at index 1 with “Riya”.

Removing Elements from a LinkedList

LinkedList provides multiple methods to remove elements. You can remove elements by value, index, or even from the beginning or end.

names.remove("Priya"); // remove by value
names.remove(0);       // remove by index
names.removeFirst();   // remove first element
names.removeLast();    // remove last element

These methods make it very flexible to manipulate data within the list.

Iterating Through a LinkedList

You can loop through a LinkedList in several ways.

Using For-Each Loop

for(String n : names) {
    System.out.println(n);
}

Using Iterator

import java.util.Iterator;

Iterator<String> it = names.iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}

Using While Loop

int i = 0;
while(i < names.size()) {
    System.out.println(names.get(i));
    i++;
}

Commonly Used Methods in LinkedList

Method Description
add() Adds an element
addFirst() Adds element at the beginning
addLast() Adds element at the end
get() Retrieves element at given index
getFirst() Gets the first element
getLast() Gets the last element
remove() Removes element by index or value
removeFirst() Removes first element
removeLast() Removes last element
clear() Removes all elements
contains() Checks if the element exists

Difference Between ArrayList and LinkedList

Feature ArrayList LinkedList
Storage Dynamic array Doubly linked list
Access Time Fast for random access Slower due to traversal
Insertion/Deletion Slower in the middle Faster in the middle
Memory Usage Less memory More memory per node
Order Maintains order Maintains order
Use Case Best for frequent read operations Best for frequent insertions/deletions

Example Program of LinkedList

import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList<String> fruits = new LinkedList<String>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        System.out.println("Fruits: " + fruits);

        fruits.addFirst("Mango");
        fruits.addLast("Grapes");
        System.out.println("Updated Fruits: " + fruits);

        fruits.remove("Banana");
        System.out.println("After Removal: " + fruits);

        for(String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

This example shows how to add, remove, and print elements using LinkedList methods.

When to Use LinkedList

You should use a LinkedList when:

  • You need frequent insertions and deletions in the list.

  • You don’t need to access elements randomly very often.

  • You want to implement a stack, queue, or deque.

If you need faster random access, use an ArrayList instead.

Summary of the Tutorial

LinkedList in Java is a flexible and efficient data structure for managing collections of elements. It provides better performance than ArrayList for adding and removing data, but slower access for random positions. It is ideal for applications that involve frequent insertions or deletions, such as task schedulers, queues, and undo operations in editors.


Practice Questions

  1. Create a LinkedList of student names, add five names, remove one from the middle, and print the final list.

  2. Write a Java program to add integers to a LinkedList and display the elements in reverse order.

  3. Create a LinkedList of fruits, insert one at the beginning and one at the end, then display all elements.

  4. Write a program that checks whether a given element exists in a LinkedList.

  5. Create a LinkedList of numbers and find the sum and average of all elements.

  6. Write a program to remove all even numbers from a LinkedList of integers.

  7. Implement a LinkedList of city names and sort them alphabetically.

  8. Create a LinkedList and demonstrate how to use addFirst(), addLast(), removeFirst(), and removeLast().

  9. Write a program to convert a LinkedList into an ArrayList and display both.

  10. Create a LinkedList of tasks (strings) and implement a simple to-do list where completed tasks are removed from the list.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top