Remove First and Last element from the LinkedList

In the previous post, we have seen how to add element at a specified index. In this post, we will see how to remove first and last element from the LinkedList.

We have methods like removeFirst() and removeLast() which are used to remove First and Last elements from the LinkedList.

Syntax:

public E removeFirst()This is used to remove the first element from the LinkedList.

public E removeLast()This is used to remove the last element from the LinkedList.

Example:

import java.util.LinkedList;

public class LinkedListEx {

	public static void main(String[] args) {
		LinkedList<String> fruits1 = new LinkedList<String>();
		fruits1.add("Orange");
		fruits1.add("Mango");
		fruits1.add("Apple");
		fruits1.add("Grapes");
		
		fruits1.removeFirst();
		System.out.println("Removed first element :"+ fruits1); //Remove Orange

		fruits1.removeLast();
		System.out.println("Removed last element :"+ fruits1);  //Remove Grapes
	}
}

Output:

Removed first element :[Mango, Apple, Grapes]
Removed last element :[Mango, Apple]


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...