Java

Java – LinkedList With Example

LinkedList is a linear data structure that is similar to Java’s arrays. However, unlike arrays, LinkedList components are connected to one another through pointers rather than being stored in consecutive places. Each entry of a linked list has a reference (or address or pointer) to the element after it.

Table of Contents

1. LinkedList Representation
2. Why do we need a Linked List?
3. Hierarchy of LinkedList class in Java
4. Java Linked List example of adding elements
5. Java Linked List example of removing elements
6. Example of LinkedList in Java
7. Methods of LinkedList class
8. Tutorials on LinkedList – In separate lessons, each method of the LinkedList class is explained in depth.

LinkedList representation

The Node is the name given to each component of a LinkedList. There are two entries in each Node of the LinkedList:

  • The element’s content
  • Pointer, address, or reference to the LinkedList’s next node.

This is how a LinkedList looks:

1. The Head of the LinkedList only holds the Address of the List’s first entry.
2. As can be seen in the figure above, the Last element of the LinkedList has null in the pointer portion of the node since it is the end of the List and does not refer to anything.
3. A simply linked list is shown in the above figure. The term “doubly linked list” refers to another complicated type variant of the LinkedList. A doubly linked list node has three components: 1) Pointer to the connected list’s preceding node 2) The element’s content 3) a pointer to the linked list’s subsequent node.

Why do we need a Linked List?

1) You should be aware that arrays are also linear data structures, but arrays have some drawbacks, including: 1) Fixed array sizes make it difficult to predict the number of elements in advance; if the declared size is insufficient, we cannot increase the size of an array; and if we declare a large size array but do not need to store that many elements, it is a waste of memory.

2) The values of array items must be stored in contiguous memory regions.

3) Adding an element to an array costs money in terms of performance since we have to move some other items to create room for the new one. As an example, suppose that an array has the following elements: 10, 12, 15, 20, 4, 5, 100. If we wish to add a new element 99 after the element with value 12, we must move all the items that come after 12 to the right in order to create room for the new element.

Similar to adding an element to the array, removing an element from the array is similarly a performance-costly operation since every element following the removed element must be shifted to the left.

The Linked List addresses these restrictions by offering the following features:
1. Because linked lists allow for dynamic memory allocation, the compiler may allocate memory at runtime and we don’t need to provide the list’s size when declaring the linked list.

2. Since linked list components are connected to one another using the reference portion of the node, which holds the address of the next node in the list, contiguous memory locations are not required.

3. Insert and delete operations in a linked list don’t cost much in terms of speed since only the pointers of the previous and next nodes need to be changed when adding or removing an entry from the list.

Hierarchy of LinkedList class in Java

Java Linked List example of adding elements

The add(), addFirst(), and addLast() methods are used in the example below to add the components to the LinkedList at the proper positions. I have included more of the LinkedList class’s essential methods at the conclusion of this article.

package com.beginnersbook;
import java.util.*;
public class JavaExample{
   public static void main(String args[]){

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

     //Adding elements to the Linked list
     list.add("Steve");
     list.add("Carl");
     list.add("Raj");

     //Adding an element to the first position
     list.addFirst("Negan");

     //Adding an element to the last position
     list.addLast("Rick");

     //Adding an element to the 3rd position
     list.add(2, "Glenn");

     //Iterating LinkedList
     Iterator<String> iterator=list.iterator();
     while(iterator.hasNext()){
       System.out.println(iterator.next());
     }
   } 
}

Output:
Java LinkedList adding elements

Java example of removing elements from the LinkedList

The add(), addFirst(), and addLast() methods are used in the example below to add the components to the LinkedList at the proper positions. I have included more of the LinkedList class’s essential methods at the conclusion of this article.

package com.beginnersbook;
import java.util.*;
public class JavaExample{
   public static void main(String args[]){

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

      //Adding elements to the Linked list
      list.add("Steve");
      list.add("Carl");
      list.add("Raj");
      list.add("Negan");
      list.add("Rick");

      //Removing First element
      //Same as list.remove(0);
      list.removeFirst();

      //Removing Last element
      list.removeLast();

      //Iterating LinkedList
      Iterator<String> iterator=list.iterator();
      while(iterator.hasNext()){
         System.out.print(iterator.next()+" ");
      }

      //removing 2nd element, index starts with 0
      list.remove(1);

      System.out.print("\nAfter removing second element: ");
      //Iterating LinkedList again
      Iterator<String> iterator2=list.iterator();
      while(iterator2.hasNext()){
         System.out.print(iterator2.next()+" ");
      }
   }
}

Output:
Java LinkedList removing elements

Example of LinkedList in Java

import java.util.*;
public class LinkedListExample {
     public static void main(String args[]) {

       /* Linked List Declaration */
       LinkedList<String> linkedlist = new LinkedList<String>();

       /*add(String Element) is used for adding 
        * the elements to the linked list*/
       linkedlist.add("Item1");
       linkedlist.add("Item5");
       linkedlist.add("Item3");
       linkedlist.add("Item6");
       linkedlist.add("Item2");

       /*Display Linked List Content*/
       System.out.println("Linked List Content: " +linkedlist);

       /*Add First and Last Element*/
       linkedlist.addFirst("First Item");
       linkedlist.addLast("Last Item");
       System.out.println("LinkedList Content after addition: " +linkedlist);

       /*This is how to get and set Values*/
       Object firstvar = linkedlist.get(0);
       System.out.println("First element: " +firstvar);
       linkedlist.set(0, "Changed first item");
       Object firstvar2 = linkedlist.get(0);
       System.out.println("First element after update by set method: " +firstvar2);

       /*Remove first and last element*/
       linkedlist.removeFirst();
       linkedlist.removeLast();
       System.out.println("LinkedList after deletion of first and last element: " +linkedlist);

       /* Add to a Position and remove from a position*/
       linkedlist.add(0, "Newly added item");
       linkedlist.remove(2);
       System.out.println("Final Content: " +linkedlist); 
     }
}

Output:

Linked List Content: [Item1, Item5, Item3, Item6, Item2]
LinkedList Content after addition: [First Item, Item1, Item5, Item3, Item6, Item2, Last Item]
First element: First Item
First element after update by set method: Changed first item
LinkedList after deletion of first and last element: [Item1, Item5, Item3, Item6, Item2]
Final Content: [Newly added item, Item1, Item3, Item6, Item2]

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button