Java Topics

LinkedList

 ✓ Used to perform insertion and deletion operations

✓ Each elements are linked using pointers/ addresses to the next node. Each element is known as node.

✓ Nodes cannot be accessed directly instead we need to start from the head and follow through the link to reach to a node.

✓ LinkedList acts as a dynamic array since size of the list automatically increases/decreases when we dynamically add or remove items.

ex :

public class LinkedList {

public static void main(String[] args) {

        LinkedList<String> l = new LinkedList<String>();

        l.add("A");

        l.add("B");

        l.addLast("C");

        l.addFirst("D");

        l.add(2,"E");

       Iterator<String> i = l.iterator();

       while(i.hasNext()) {

       System.out.println(i.next()+" ");

       }

}

}

Output:

D

A

E

B

C

NOTE:

When exactly we will go with the LinkedList instead of ArrayList?

    Suppose if we want to insert or delete elements from the list, then shifting of the elements will happen in arraylist and it will affect the performance.

    Where as in LinkedList shifting of elements is not happen, instead of only pointer of the previous and next node require changes.

    So, to perform insert and delete operations will go with LinkedList.