Introduction
What a fantastic job James Gosling did by creating Java. According to Github, Java is one of the most popular programming languages, with about nine million developers using it.
It's a straightforward, object-oriented programming language that's both secure and robust. The Java runtime is fantastic, and it's one of the best languages for data structures and algorithms. In the Java library, practically every data structure is predefined, and a linked list is one of them.
Today we'll look at the Linked List’s remove() method in Java.
There are three versions of the Linked List remove method in Java.
- remove()- This takes no parameters and removes the first node of the linked list.
- remove(int INDEX)- This takes one parameter INDEX and removes the INDEXth node in the linked list.
- remove(Object OBJ)- This one takes one parameter, OBJ, which is the object to be removed from the linked list.
Let’s explore each variation of remove() one by one.
See, Application of Linked Lists
remove()
The Java.util.LinkedList.remove() method will remove the first element from the linked list.
Example
Program
import java.io.*;
// Library that includes all Linked List's methods.
import java.util.LinkedList;
// Class that removes the first element of the linked list using the ’remove()’ method.
public class LinkedListRemove{
public static void main(String args[]){
// Initialize the Linked List.
LinkedList<String> list = new LinkedList<String>();
// Inserting nodes in the linked list it usig ’add()’ method.
list.add("CodingNinja");
list.add("Coding Ninjas Studio");
list.add("LinkedList");
// Printing the List before Remove.
System.out.println("List before removal: " + list);
// Removing the head node using remove() method.
list.remove();
// Printing the List after removal.
System.out.println("List after removal: " + list);
}
}
Output
List before removal: [CodingNinja, Coding Ninjas Studio, LinkedList]
List after removal: [Coding Ninjas Studio, LinkedList]
Recommended Topic, Floyds Algorithm