LinkedList pollLast() method with example in java

Published by user on

The pollLast() method of LinkedList retrieves and removes the last element of this linked list. It returns null if this list is empty.

Syntax

Object pollLast()

Parameters

It does not take any parameter

Return Value

It returns the removed element in this linked-list or null if the list is empty.

Program 1

import java.util.LinkedList;

public class LinkedListPollLastExample {

	public static void main(String[] args) {

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

		System.out.println("Linked List elements: " + oddNumbers);
		oddNumbers.pollLast();
		System.out.println("Linked List elements after removing last element: " + oddNumbers);
	}
}

Output

Linked List elements: [5, 7, 9, 11]
Linked List elements after removing last element: [5, 7, 9]

Program 2

import java.util.LinkedList;

public class LinkedListPollLastExample {

	public static void main(String[] args) {

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

		System.out.println("Linked List elements: " + oddNumbers);
		oddNumbers.clear();
		System.out.println("Linked List elements after clear() call: " + oddNumbers);
		System.out.println("Last element in this linked-list: " + oddNumbers.pollLast());
	}
}

Output

Linked List elements: [5, 7, 9, 11]
Linked List elements after clear() call: []
Last element in this linked-list: null
Categories: Java

0 Comments

Leave a Reply

Avatar placeholder

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