What is LinkedList in Java?

A linked list is a data structure made of a chain of node objects. Each node contains a value and a pointer to the next node in the chain. Linked lists are preferred over arrays due to their dynamic size and ease of insertion and deletion properties.

Here is the declaration for Java LinkedList class:

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, Serializable 

LinkedList in Java implements the abstract list interface and inherits various constructors and methods from it. A doubly linked list is used to store the elements. LinkedList also implements the Deque interface.

Thus, this sequential data structure can be used as a list, stack or queue.

svg viewer

Example

import java.util.*;
public class LL{
public static void main(String args[]){
// creating Linked List
LinkedList<Character> ll = new LinkedList<Character>();
// adding elements `b` and `g` missing
ll.add('a'); ll.add('c'); ll.add('d');
ll.add('e'); ll.add('f'); ll.add('h');
System.out.println(ll);
// adding while specifying locations
ll.add(5, 'g'); ll.add(1, 'b');
System.out.println(ll);
// removing using different functions
ll.removeFirst(); ll.remove(0); ll.removeLast();
System.out.println(ll);
// traverse list from tail
Iterator i=ll.descendingIterator();
while(i.hasNext()){
System.out.println(i.next());
}
// printing out size of list
System.out.println("List Size: " + ll.size());
}
}
Copyright ©2024 Educative, Inc. All rights reserved