MadAlgos Blog
Basic operations on LinkedList ep02
Traversing LinkedList in Java
A joke to begin with
Why did the programmer become a tour guide for linked lists?
Because they loved taking visitors on a never-ending journey through their favorite data structure, always saying, "Next! Next! Next!"
hahaha😂
Traversing a linked list is an essential operation in data structures and programming.
Linked lists are a popular data structure consisting of nodes connected by pointers, where each node holds data and a reference to the next node.
When we talk about traversing a linked list, we refer to the process of visiting each node in sequence, starting from the head node and moving towards the tail.
This iterative process allows us to access, manipulate, or analyze the data stored in each node, enabling us to perform various operations efficiently.
Traversing a linked list forms the foundation for other operations such as searching, insertion, deletion, and more. It's an important concept to understand for anyone working with linked lists or data structures in general.
In the computational realm, we have five methods for iterating over a LinkedList :
- Using for loop
- Using while loop
- Using enhanced for loop
- Using Iterator
- Using forEach() method
Using for loop :
In Java, the LinkedList class does not provide direct access to elements by index. Therefore, using a for loop with an index-based approach may not be the most efficient way to traverse a LinkedList.
However, if you still prefer to use a for loop, you can convert the LinkedList to an array and then iterate over the array using the for loop.
Here's an example:
import java.util.LinkedList; public class LinkedListTraversalExample
{ public static void main(String[] args)
{ LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Apple"); linkedList.add("Banana"); linkedList.add("Orange");
// Converting LinkedList to an array String[] array = linkedList.toArray(new String[linkedList.size()]);
// Using a for loop to traverse the array for (int i = 0; i < array.length; i++) { String element = array[i];
System.out.println(element); } } }
In this example, we first create a LinkedList of strings and add some elements to it. Then we convert the LinkedList to an array using the toArray() method. The toArray() method takes an array of the desired type as an argument and returns an array representation of the LinkedList.
Finally, we use a for loop to iterate over the array, accessing each element by index and printing it.
The output will be:
Apple Banana Orange
However, please note that converting the LinkedList to an array adds an extra step and may consume additional memory, especially for large lists. The iterator or for-each loop approaches are generally preferred for efficient traversal of a LinkedList in Java.
There’s another way through which we can traverse a LinkedList using for-loop :
The LinkedList in Java is a component of the collection framework found in the java.util package. It serves as an implementation of the LinkedList data structure, which stores elements in a non-contiguous manner within the memory.
Here's is the code :
import java.util.LinkedList;
public class MADAlgos {public static void main(String[] args) {// Creating a LinkedList of Integer typeLinkedList<Integer> linkedList = new LinkedList<>();
// Inserting some Integer values to LinkedListlinkedList.add(4);linkedList.add(3);linkedList.add(2);linkedList.add(1);
// LinkedList after insertions: [4, 3, 2, 1]
// Calling the function to iterate our LinkedList UsingForLoopUsingForLoop(linkedList);}
// Function to iterate the LinkedList using a simple for looppublic static void UsingForLoop(LinkedList<Integer> linkedList) {System.out.print("Iterating the LinkedList using a for loop: ");for (int i = 0; i < linkedList.size(); i++) {System.out.print(linkedList.get(i) + " ");}}}
Here's the output:
Iterating the LinkedList using a for loop: 4 3 2 1
Using iterator :
To perform iteration on the LinkedList using the iterator, we begin by creating an iterator for the given list.
Then, we continuously retrieve and print the next element using the next() method as long as there are more elements available within the LinkedList.
We verify the presence of the next element by utilizing the hasNext() method of the LinkedList.
Here’s a code using iterator :
import java.util.Iterator; // Importing LinkedList class from // java.util package import java.util.LinkedList; public class MADAlgos { public static void main(String[] args) { // Creating a LinkedList of Integer Type LinkedList<Integer> linkedList = new LinkedList<>(); // Inserting some Integer values to our LinkedList linkedList.add(5); linkedList.add(1); linkedList.add(4); linkedList.add(10); linkedList.add(7); // LinkedList after insertions : [5, 1, 4, 10, 7] // Calling the function to iterate our LinkedList iterateUsingIterator(linkedList); } // Function to iterate the Linked List using Iterator public static void iterateUsingIterator(LinkedList<Integer> linkedList){ System.out.print("Iterating the LinkedList using Iterator : "); // Creating an Iterator to our current LinkedList Iterator itr = linkedList.iterator(); // Inside the while loop we check if the next element // exists or not if the next element exists then we print // the next element and move to it otherwise we come out // of the loop // hasNext() method return boolean value // It returns true when the next element // exists otherwise returns false while(itr.hasNext()){ // next() return the next element in the iteration System.out.print(itr.next() + " "); } } }
Here's the output:
Iterating the LinkedList using Iterator : 5 2 4 10 7
Homework
Learn about how to iterate LinkedList using the following :
- Using while loop
- Using enhanced for loop
- Using forEach() method
Hope you enjoyed reading
Dance with your LinkedList tunes!
Happy learning
Now what ?
Follow us on MADAlgos
Check the following blog for LinkedList
Introduction to LinkedList
https://madalgos.in/blog-space/27
https://madalgos.in/blog-space/28
https://madalgos.in/blog-space/29
Basic opertaions on LinkedList
https://madalgos.in/blog-space/30