In this tutorial we will learn how to remove First and Last elements from LinkedList. In the few last posts we shared following tutorials:
1) Removing elements from a specific index
2) Removing specific element from LinkedList
Example
We have used removeFirst() method to remove first and removeLast() method to remove last element from LinkedList. Method definition and description are as follows:
1) public E removeFirst(): Removes and returns the first element from this list.
2) public E removeLast(): Removes and returns the last element from this list.
Complete Code:
import java.util.LinkedList;
public class RemoveExample {
public static void main(String[] args) {
// Create a LinkedList
LinkedList<String> linkedlist = new LinkedList<String>();
// Add elements to LinkedList
linkedlist.add("Item1");
linkedlist.add("Item2");
linkedlist.add("Item3");
linkedlist.add("Item4");
linkedlist.add("Item5");
// Displaying Elements before remove
System.out.println("LinkedList Elements are:");
for(String str: linkedlist){
System.out.println(str);
}
// Removing First element
Object firstElement = linkedlist.removeFirst();
System.out.println("\nElement removed: "+ firstElement);
// Removing last Element
Object lastElement = linkedlist.removeLast();
System.out.println("Element removed: "+ lastElement);
// LinkedList elements after remove
System.out.println("\nList Elements after Remove:");
for(String str2: linkedlist){
System.out.println(str2);
}
}
}
Output:
LinkedList Elements are: Item1 Item2 Item3 Item4 Item5 Element removed: Item1 Element removed: Item5 List Elements after Remove: Item2 Item3 Item4
Leave a Reply