Remove first and last element from a linked list. ****Java*****
Remove first and last element from a linked list. ****Java*****
There is a predefined class or package in java that is java.util.LinkedList. This package have methods to remove first and last element in linked list that are removeFirst() and removeLast().
Program to remove first and last element in java :-
import java.util.LinkedList;
public class Linklis
{
public static void main (String[] args) {
// Here we are creating linked list that is "lt"
LinkedList<String> lt = new LinkedList<String>();
// add() method is used to insert or add elements in linked list
lt.add("My");
lt.add("Name");
lt.add("is");
lt.add("Jack");
lt.add("John");
// Printing the list
System.out.println("LinkedList:\t" + lt);
// Removing first element or head First list using removeFirst() method
System.out.println("Removing the First element :\t" + lt.removeFirst());
// Now the list after removing first element
System.out.println("Now the list elements are :\t" + lt);
// Removing Last element or tail of list using removeLast() method
System.out.println("Removing the Last element :\t" + lt.removeLast());
// Now the list after removing Last element
System.out.println("Now the list elements are :\t" + lt);
}
}
Step by step
Solved in 2 steps with 1 images