How to get first and last element of a linked list in Java

Hello guys, in today's post I will teach you how to get the first and last element of a linked list in Java. This is a common coding problem but we will see it from different angles. In Java, you don't need to write and create your own LinkedList, there is a built-in class called java.util.LinkedIn and you can use that class whenever you need a linked list data structure. This class provides method getFirst() and getLast() to retrieve the first and last element from a linked list. In this article, I will show you how to use that method to get the first and last node from a given linked list.

How to get the first and last element of a linked list in Java

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.


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


In this program, 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 expected value or not.

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 this Data Structure and Algorithms master class from Udemy to start with.

How to get first and last element of a linked list in Java


That's all about how to get the first and last element form a given LinkedList in Java. This one was a simple example. If you guys like this kind of to-the-point article explaining simple methods and concepts of Java then tell us in comments.

Further Reading

Thanks for reading this article so far. If you like this Java linked list tutorial s and my explanation then please share 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 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

No comments:

Post a Comment