LinkedList removeLastOccurrence() method with example in java

Published by user on

The removeLastOccurrence(E element) method of LinkedList removes the last occurrence of the specified element from this linked list. It returns true if the list contains the specified element. It returns true if the list contains the specified element.

Syntax

boolean removeLastOccurrence(Element e)

Parameters

e is the element to remove from this linked-list

Return Value

true if the linked-list contains the specified element

Program

import java.util.LinkedList;

public class LinkedListRemoveLastOccurrenceExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);
		oddNumbers.add(9);

		System.out.println("Linked List elements: " + oddNumbers);

		System.out.println(oddNumbers.removeFirstOccurrence(9));
		System.out.println("Linked List  after removing the first occurrence of element 9: " + oddNumbers);
		System.out.println(oddNumbers.removeFirstOccurrence(8));//returns false as list does not contain 8
	}
}

Output

Linked List elements: [5, 7, 9, 11, 9]
true
Linked List  after removing the first occurrence of element 9: [5, 7, 11, 9]
false
Categories: Java

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *