Java Program to Get the First and the Last Element of a Linked List
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The given task is to retrieve the first and the last element of a given linked list.
Properties of a Linked List:
- Elements are stored in a non-contiguous manner.
- Every element is an object which contains a pointer to the next element.
Approach 1: Using in-built libraries
Use the pre-built LinkedList class in the java.util package to build a Linked List and use the pre-defined methods to fetch the respective values.
Example: Below is the implementation of the above approach:
Java
// Java Program to get the first and the last element of a // Linked List // Importing the Linked List class from the util package import java.util.LinkedList; class AccessFirstAndLastElements { public static void main(String[] args) { // Initializing the Linked List LinkedList<Integer> ll = new LinkedList<>(); // Adding elements to the Linked List ll.add(2); ll.add(5); ll.add(5); ll.add(7); ll.add(10); ll.add(6); // Getting the first element System.out.println("First Element is : " + ll.getFirst()); // Getting the last element System.out.println("Last Element is : " + ll.getLast()); } } |
Output First Element is : 2 Last Element is : 6
Time Complexity: getFirst() takes O(1) time and getLast() takes O(n) where n is the number of elements in the Linked List.
Approach 2: Without using in-built methods
- Create a generic Node class.
- Create our very own Linked List class using the Node class.
- Create the required add(), getFirst() and getLast() methods.
- Initialize the Linked List.
- Use the respective get methods to fetch the values.
Example: Below is the implementation of the above approach:
Java
// Java program to get the first and last element from a // Linked List // A Generic Node class is used to create a Linked List class Node<E> { // Data Stored in each Node of the Linked List E data; // Pointer to the next node in the Linked List Node<E> next; // Node class constructor used to initializes the data // in each Node Node(E data) { this.data = data; } } class LinkedList<E> { // Points to the head of the Linked List // i.e the first element Node<E> head; int size = 0; // Addition of elements to the tail of the Linked List public void add(E element) { // Checks whether the head is created else creates a // new one if (head == null) { head = new Node<>(element); size++; return; } // The Node which needs to be added at // the tail of the Linked List Node<E> add = new Node<>(element); // Storing the instance of the // head pointer Node<E> temp = head; // The while loop takes us to the tail of the Linked // List while (temp.next != null) { temp = temp.next; } // New Node is added at the tail of // the Linked List temp.next = add; // Size of the Linked List is incremented as // the elements are added size++; } // Retrieves the first element of the Linked List public E getFirst() throws Exception { // Throws an Exception if the List is empty if (head == null) { throw new Exception( "No elements found in Linked List"); } // Returns the first element return head.data; } // Retrieves the last element of the Linked List public E getLast() throws Exception { // Throws an Exception if the List is empty if (head == null) { throw new Exception( "No elements found in Linked List"); } Node<E> temp = head; // The while loop takes us to the tail of the Linked // List while (temp.next != null) { temp = temp.next; } // Returns the last element return temp.data; } } class AccessFirstAndLastElements { public static void main(String[] args) throws Exception { // Initializing the Linked List LinkedList<Integer> ll = new LinkedList<>(); // Adding elements to the Linked List ll.add(2); ll.add(5); ll.add(5); ll.add(7); ll.add(10); ll.add(6); // Getting the first element System.out.println("First Element is : " + ll.getFirst()); // Getting the last element System.out.println("Last Element is : " + ll.getLast()); } } |
Output First Element is : 2 Last Element is : 6
Time Complexity: getFirst() takes O(1) time and getLast() takes O(n) where n is the number of elements in the Linked List.
Article Tags :
Java
Java Programs
Technical Scripter
Technical Scripter 2020
Practice Tags :
Java
Read Full Article
Retrieve the last element from a LinkedList in Java
Java 8Object Oriented ProgrammingProgramming
The last element of a Linked List can be retrieved using the method java.util.LinkedList.getLast() respectively. This method does not require any parameters and it returns the last element of the LinkedList.
A program that demonstrates this is given as follows −
JavaScript.Linked Lists. Get last element in the list. Clear the list.
Yuriy Berezskyy Follow
Jul 23, 2020 · 3 min read
Hello everyone and welcome back to our blog. Today we are going to discus and learn how to write a new method for linked list. As always I would like to pay attention one thing it’s previous blogs. I will recommend to start with them.
Link to previous blogpost:
Example:
package com.w3spoint; import java.util.LinkedList; public class Test { public static void main(String args[]){ LinkedList<String> linkedList = new LinkedList<String>(); linkedList.add("Jai"); linkedList.add("Mahesh"); linkedList.add("Naren"); linkedList.add("Vivek"); linkedList.add("Vishal"); linkedList.add("Hemant"); System.out.println("Actual LinkedList:"+linkedList); System.out.println("Last Element: "+linkedList.getLast()); System.out.println("Last Element: "+linkedList.peekLast()); } } |
package com.w3spoint; import java.util.LinkedList; public class Test { public static void main(String args[]){ LinkedList<String> linkedList = new LinkedList<String>(); linkedList.add("Jai"); linkedList.add("Mahesh"); linkedList.add("Naren"); linkedList.add("Vivek"); linkedList.add("Vishal"); linkedList.add("Hemant"); System.out.println("Actual LinkedList:"+linkedList); System.out.println("Last Element: "+linkedList.getLast()); System.out.println("Last Element: "+linkedList.peekLast()); } }