How to Remove LinkedList First and Last Elements in Java


In this example, we will learn the common method to remove first and last elements of LinkedList object in Java.

Source Code

package com.beginner.examples;

import java.util.LinkedList;

public class RemoveFirstLastElementsLinkedList {

	public static void main(String[] args) {
		
		//create LinkedList.
		LinkedList linkedList = new LinkedList();
		
		linkedList.add("A");
		linkedList.add("B");
		linkedList.add("C");
		linkedList.add("D");
		
		/*
		 * Use removeFirst() and removeLast() method tp remove first and last elements. 
		 */
		linkedList.removeFirst();
		linkedList.removeLast();
		
		System.out.println(linkedList);
		
	}

}

Output:

[B, C]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments