The code demonstrates how to retrieve elements from both ends of a LinkedList in Java. The Retrieve_BothEnds class contains a main method where a LinkedList object named list is created and populated with string elements using the add method.
The System.out.println statements are used to print the initial state of the list linked list. Then, the following methods are used to retrieve elements from the head (first) and tail (last) of the list linked list:
The System.out.println statements are used to print the retrieved elements from both ends of the list linked list.
As a result, the head and tail elements of the list linked list will be retrieved and printed, as demonstrated by the output of the System.out.println statements. Note that the peek() and peekFirst() methods will return null when the list is empty, whereas the other methods may throw NoSuchElementException in such cases.
import java.util.*; public class Retrieve_BothEnds { public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.add("Apple"); list.add("Mango"); list.add("Pineapple"); list.add("Cherry"); list.add("Guava"); list.add("Banana"); list.add("Watermelon"); System.out.println(list); //Retrieving the elements from the head System.out.println(list.element()); System.out.println(list.getFirst()); System.out.println(list.peek()); System.out.println(list.peekFirst()); //Retrieving the elements from the tail System.out.println(list.peekLast()); System.out.println(list.getLast()); } }
[Apple, Mango, Pineapple, Cherry, Guava, Banana, Watermelon] Apple Apple Apple Apple Watermelon Watermelon
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions