Get last node in linked list Java

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.
Input: [2, 5, 5, 7, 10, 6] Output: First element is : 2 Last element is : 6 Input: [1] Output: First element is : 1 Last element is : 1

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 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 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.

Get last node in linked list Java




Article Tags :

Java

Java Programs

Technical Scripter

Technical Scripter 2020

Practice Tags :

Java

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 −

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()); } }

JavaScript.Linked Lists. Get last element in the list. Clear the list.

Get last node in linked list Java

Yuriy Berezskyy

Follow

Jul 23, 2020 · 3 min read

Get last node in linked list Java

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:

Getting First and the Last Element of LinkedList in Java - Example

Here is our sample Java program to find the first and last object from LinkedList in Java. We will be using Java's Collection framework API to get our done. In this example, I have created a linked list of String to store different programming languages. You can store objects into LinkedList by calling add() method.


This method encapsulates data into a private static nested class Node, which represent a node in a doubly linked list and keep reference of both previous and next node in linked list. Also this method adds the new element at the end of linked list i.e. on the tail, which means last method you add into linked list will be the last element in the LinkedList itself.


The angle bracket you see while creating instance of LinkedList is known as diamond operator, added backed in Java 7 and help you to avoid declaring types on right hand side of assignment operator as well. The compiler can now infer it by looking at left-hand side. You should use it every time you are using JDK 1.7 to reduce at least a little bit of boiler plate coding.



Get last node in linked list Java




Now coming back to our task, how do we retrieve the first and last element from linked list? Of course we don't know which elements are added, unlike this example, where we know.


Since a linked list is a sequential data structure, by looking at how you add elements you can guess which one is first and which one is last, but this example is more for situation, where you receive a linked list from other part of your application and need to find first and last element.

LinkedList has getFirst() and getLast() method to retrieve first and last element from LinkedList in Java. I would have liked just first() and last() method but anyway.

import java.util.LinkedList; /** * Java program to find first and last element of linked list in Java. */ public class LinkedListDemo{ public static void main(String args[]) { LinkedList programmingLanguages = new LinkedList<>(); programmingLanguages.add("Java"); programmingLanguages.add("Perl"); programmingLanguages.add("Ruby"); programmingLanguages.add("Python"); programmingLanguages.add("C"); programmingLanguages.add("C++"); programmingLanguages.add("C#"); programmingLanguages.add("Scala"); // getting first element of linked list in Java String first = programmingLanguages.getFirst(); System.out.printf("First element of LinkedList is : %s %n", first); // getting last element from linked list in Java String last = programmingLanguages.getLast(); System.out.printf("Last element of LinkedList is : %s %n", last); } } Output: First element of LinkedList is : Java Last element of LinkedList is : Scala
That's all about how to find first and last node of a linked list in Java. Remember, Java's implementation of linked list data structure is a doubly linked list, which means each node has reference to both previous and next node. You can iterate over LinkedList but iterator doesn't guarantee any order, so beware of that as well.

If you are hungry to know more about linked list in Java, check out these amazing articles :

  • What is difference between LinkedList and ArrayList in Java? (answer)
  • How to find middle element of linked list in Java? (solution)
  • What is difference between array and linked list in data structure? (answer)
  • How to find if linked list has loop in it? (solution)
  • How to find length of singly linked list in Java? (solution)
  • Difference between List, Set and Map in Java? (answer)
  • When to use LinkedList over ArrayList in Java? (answer)

How to get the first and last objects of a linked list in Java? Example

The following example shows how to get the first and last element of a linked list with the help of LinkedList.getFirst() and LinkedList.getLast() of LinkedList class in Java.


In this program, you can see that we have created a new LinkedList object and then added 5 String objects into it, which are nothing but numbers 100 to 500 in multiples of 100. Afte that we have used the getFirst() and getLast() method to retrieve the first and last element and printed them using System.out.println(), the oldest way to print something in Java.


And, if you want to learn more about linked list data structure itself and learn how to create your own linked list in Java using object-oriented programming then you can also check out thisData Structure and Algorithms master classfrom Udemy to start with.

Get last node in linked list Java


Anyway, here is our complete Java program which demonstrates how to use the LinkedList class for storing and retrieving objects.

import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList lList = new LinkedList(); lList.add("100"); lList.add("200"); lList.add("300"); lList.add("400"); lList.add("500"); System.out.println("The first element of LinkedList is: " + lList.getFirst()); System.out.println("The last element of LinkedList is: " + lList.getLast()); } } Result: The above code sample will produce the following result. The first element of LinkedList is:100 The last element of LinkedList is:500



You can see that, we have first added 5 numbers from 100 to 500 into then LinkedList and then use the getFirst() and getLast() method to get the first and last element. The code return 100 and 500 which is as per the expected result. I have printed the output but you can also write JUnit test cases with an assert statement to check if the returned value matches with the expected value or not.

That's all about how to get the first and last element from a given LinkedList in Java. This one was a simple example but you learned how to use the LinkedList data structure in Java. If you guys like this kind of to-the-point article explaining simple methods and concepts of Java then tell us in the comments and I will write more of this. As always, your feedback is very important to us to produce better tutorials and guides.



Other Data Structure and Algorithms Articles You may like

  • Top 30 Array Interview Questions for Programmers
  • Top 30 linked list interview questions for Programmers
  • 7 Best Courses to learn Data Structure
  • 10 Books to Prepare for Coding Interviews
  • 7 Best Courses to learn Data Structure and Algorithms
  • 10 Books to learn Computer Science Algorithms.
  • Top 5 Websites to learn Java Coding for FREE
  • 5 Website to Practice Coding Questions for Interviews
  • Data Structure and Algorithm Made Easy in Java

Thanks for reading this article so far. If you like this Java linked list tutorials and my explanation then please share it with your friends and colleagues. If you have any questions or doubt then please write a comment and I'll try to find an answer for you.

P. S. - If you are new to the Java Programming world and want to learn Data Structure and Algorithms in Java and looking for some free courses to start with then you should also check out my list of FREE Data Structure and Algorithm courses for Java Developers which contains free data structure and algorithms courses from Udemy, Coursera, and other popular online websites.