A linked list is a collection of linear data elements. Each element (node) contains data and reference parts. The data part has the value and the reference part has the address link to the next element. The elements are not indexed, so random access like an array is not possible. Instead, we traverse from the beginning of the list and access the elements.
In Java, the
LinkedListis theimplementation of the List and Deque interfaces. The doubly-linked list A kind of linked list. Each node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. LinkedListclass is present in thejava.utilpackage.
removeLastOccurrence methodThe removeLastOccurrence method can be used to remove the last occurrence of the specified element in the LinkedList.
public boolean removeLastOccurrence(Object o);
This method takes the element to be removed from the list as an argument.
This method returns true if the specified element is present in the specified element.
The code below demonstrates how to use the removeLastOccurrence method:
import java.util.LinkedList;class LinkedListRemoveLastOccurrenceExample {public static void main( String args[] ) {LinkedList<String> list = new LinkedList<>();list.add("1");list.add("2");list.add("1");System.out.println("The list is " + list);System.out.println("Is element present " + list.removeLastOccurrence("1"));System.out.println("The list is " + list);}}
In the code above:
LinkedList class.import java.util.LinkedList;
LinkedList
object with the name list.LinkedList<String> list = new LinkedList<>();
add method of the list object to add three elements ("1","2","3") to the list.list.add("1");
list.add("2");
list.add("3");
removeLastOccurrence method to remove the last occurrence of the element "1". The element "1" is present in two indexes, 0 and 2. After calling this method, the element at index 2 will be removed.list.removeLastOccurrence("1"); // true
list; // ["1", "2"]