DEV Community

Cover image for Creating of LinkedList
Samanvi Thota
Samanvi Thota

Posted on • Updated on

Creating of LinkedList

The LinkedList class of the Java collections framework provides the functionality of the linked list data structure (doubly linkedlist).

Each element in a linked list is known as a node. It consists of 3 fields:
Prev - stores an address of the previous element in the list. It is null for the first element
Next - stores an address of the next element in the list. It is null for the last element
Data - stores the actual data

  • Syntax for creating a LinkedList:
LinkedList<Type> linkedList = new LinkedList<>(); 
Enter fullscreen mode Exit fullscreen mode

Here, Type indicates the type of a linked list. For example,

// create Integer type linked list

LinkedList<Integer> linkedList = new LinkedList<>();

// create String type linked list

LinkedList<String> linkedList = new LinkedList<>(); 
Enter fullscreen mode Exit fullscreen mode
  • Example Program to create LinkedList:
import java.util.LinkedList;

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

    // create linkedlist
    LinkedList<String> animals = new LinkedList<>();

    // Add elements to LinkedList
    animals.add("Dog");
    animals.add("Cat");
    animals.add("Parrot");
    System.out.println("LinkedList: " + animals);
  }
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

LinkedList: [Dog, Cat, Parrot]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)