In this article, we will understand how to remove elements from the linked-list.
The java.util.LinkedList class operations perform we can expect for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Below is a demonstration of the same −
Suppose our input is −
The list is defined as: [Java, Scala, Python, JavaScript, C++]
The desired output would be −
The list after removing all the elements is: [Python, JavaScript, C++]
Algorithm
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Display the result Step 5 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.LinkedList;
public class Demo {
public static void main(String args[]){
LinkedList<String> input_list = new LinkedList<String>();
input_list.add("Java");
input_list.add("Scala");
input_list.add("Python");
input_list.add("JavaScript");
input_list.add("C++");
System.out.println("The list is defined as: " + input_list);
input_list.remove();
input_list.remove();
System.out.println("The list after removing all the elements is: " + input_list);
}
}Output
The list is defined as: [Java, Scala, Python, JavaScript, C++] The list after removing all the elements is: [Python, JavaScript, C++]
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.LinkedList;
public class Demo {
static void remove_element(LinkedList<String> input_list){
input_list.remove();
input_list.remove();
System.out.println("The list after removing all the elements is: " + input_list);
}
public static void main(String args[]){
LinkedList<String> input_list = new LinkedList<String>();
input_list.add("Java");
input_list.add("Scala");
input_list.add("Python");
input_list.add("JavaScript");
input_list.add("C++");
System.out.println("The list is defined as: " + input_list);
remove_element(input_list);
}
}Output
The list is defined as: [Java, Scala, Python, JavaScript, C++] The list after removing all the elements is: [Python, JavaScript, C++]