🌐
AlphaCodingSkills
alphacodingskills.com › java › ds › java-linked-list-traversal.php
Java - Linked List Traversal - AlphaCodingSkills
//node structure class Node { int data; Node next; }; class LinkedList { Node head; LinkedList(){ head = null; } //Add new element at the end of the list void push_back(int newElement) { Node newNode = new Node(); newNode.data = newElement; newNode.next = null; if(head == null) { head = newNode; } else { Node temp = new Node(); temp = head; while(temp.next != null) temp = temp.next; temp.next = newNode; } } //display the content of the list void PrintList() { Node temp = new Node(); temp = this.head; if(temp != null) { System.out.print("The list contains: "); while(temp != null) { System.out.p
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › traversal-of-singly-linked-list
Traversal of Singly Linked List - GeeksforGeeks
August 17, 2026 - The process of traversing a singly linked list involves printing the value of each node and then going on to the next node and print that node's value also and so on, till we reach the last node in the singly linked list, whose next node is null.
Discussions

linked list - Optimal ways to Traverse through a LinkedList - Java - Stack Overflow
The Situation I have a interview with TripAdvisor tomorrow and I decided for practice to create my own custom LinkedList. I'm trying to figure out the best way to traverse through it. Primary Qu... More on stackoverflow.com
🌐 stackoverflow.com
How do you efficiently loop through a linkedlist?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
14
12
February 5, 2022
Is it possible to traverse a linked list in a for loop?
You can write an iterator for your class, and then you can just use a regular for loop on any ListNode: class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def __iter__(self): return ListNodeIterator(self) class ListNodeIterator: def __init__(self, node): self.node = node def __next__(self): if self.node is not None: val = self.node.val self.node = self.node.next return val else: raise StopIteration linked_list = ListNode(1, ListNode(2, ListNode(3, None))) for n in linked_list: print(n) An iterator is just an object that has a __next__ function, which returns a value and moves the iterator forward. It essentially keeps track of where the for loop is right now. Your list can be iterated by multiple threads at the same time, and those will need different iterators, so the ListNode can't be an iterator itself - it has a __iter__ method that creates one. More on reddit.com
🌐 r/learnpython
10
2
July 20, 2021
Traversing a Linked List without Iterators
Could you post a test case and the actual error messages? The main issue is that: let Some(next_node) = &curr_node.borrow().next Gives you a shared reference i.e. &Box>, and you are then trying to move out of that to reassign to curr_node (i.e. making curr_node the owner). I hit this a similar before working with trees, but looking at my code I just hacked around it with .clone() The main issue you have is that you can't have both curr_node and head.next owning the same Box. Since you don't need to mutate things maybe you can use an Rc here. Or you could remove it from head.next and take ownership (since you never need to re-iterate in the list) using .take() on the option - but head will need to be mutable in that case. Have you read Learning Rust with entirely too many linked lists ? - it has tonnes of tricks for helping with these cases (but the general message is avoid Linked Lists!). More on reddit.com
🌐 r/learnrust
9
April 30, 2020
🌐
Javatpoint
javatpoint.com › traversing-in-singly-linked-list
Traversing in Singly Linked List - javatpoint
Inorder Tree Traversal without recursion and stack! Maximum product of indexes of next greater on left and right ... Heap memory vs. stack memory ... Announcement! We are excited to announce that we are moving from JavaTpoint.com to TpointTech.com on 10th Feb 2025. Stay tuned for an enhanced experience with the same great content and even more features. Thank you for your continued support! in singly linked list is performed in order to find the location of a particular element in the list.
🌐
GeeksforGeeks
geeksforgeeks.org › problems › linkedlist-traversal › 1
Linked List Traversal | Practice | GeeksforGeeks
Given an LinkedList list that contains integer elements. The task is to iterate through the given list and print its elements. Examples: Input: list = [1, 2, 3, 4] Output: 1 2 3 4 Explanation: Simply iterate through the ll and print the elements. Inp
🌐
Emory
cs.emory.edu › ~cheung › Courses › 255 › Syllabus › 7-ARM › traverse-lists.html
Traversing linked lists
The · list starts at the location given by the variable · head: List traversal example 1: sum the values stored in a list · The Java code to find the · sum stored in all elements of the list: The · flow chart of the above program is: Note: ARM assembler code that implements this ·
🌐
Tutorialsinhand
tutorialsinhand.com › tutorials › java-programs › java-collection-traversal-programs › java-program-to-traverse-linkedlist.aspx
Java program to traverse linkedlist
February 1, 2020 - In this java programs tutorial, our task is to write a java program to traverse linked list using iterator, to traverse linked list using list iterator
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-search-an-element-in-a-linked-list
Java Program to Search an Element in a Linked List - GeeksforGeeks
July 23, 2025 - A for loop is used to traverse through the elements present in the Linked List. Below is the implementation of the above approach: ... // Java Program to find an element in a Linked List // Importing the Linked List class import java.util.L...
🌐
w3resource
w3resource.com › java-exercises › collection › java-collection-linked-list-exercise-3.php
Java - Iterate all elements in a linked list from the first
May 22, 2025 - import java.util.LinkedList; import java.util.Iterator; public class Exercise3 { public static void main(String[] args) { // create an empty linked list LinkedList<String> l_list = new LinkedList<String>(); // use add() method to add values in the linked list l_list.add("Red"); l_list.add("Green"); l_list.add("Black"); l_list.add("White"); l_list.add("Pink"); // set Iterator at specified index Iterator p = l_list.listIterator(1); // print list from second position while (p.hasNext()) { System.out.println(p.next()); } } } ... Write a Java program to iterate through a linked list starting from a user-defined index and print the remaining elements.
Top answer
1 of 1
5

I would change your traverse function to be more like this:

public void traverse(){
  Node<T> pointer = head;

  while (pointer != null){
    System.out.println(pointer.getData());
    pointer = pointer.getLink();
  }
}

Also it is common to represent the Node class as a private inner class of LinkedList because it is not typically needed anywhere else.

As far as the interview itself goes, traversal questions are more typical for binary-trees (eg. print out the elements in sorted order). LinkedList questions are more focussed on the remove/insert operations which both require careful attention to the edge cases (what happens when you remove the head for example). A more advanced LinkedList question would ask how to detect a cycle, I would make sure that I knew at least one method of doing this (have a look at the Tortoise and the Hare algorithm).

EDIT:

Algorithm questions will nearly always be from the following list:

  • String manipulation such as:
    • Reverse String
    • Count how many times each letter appears in a given String (use a Map for this)
  • LinkedList questions such as:
    • How to remove a node, pay close attention to edge cases such as removing the head
    • How to reverse a linkedList (make the Tail the Head)
  • Binary Tree questions such as:
    • In-order traversal
    • If there is a BTree balancing question you won't need to implement it, just understand that a completely unbalanced Binary Tree is simply a Linked List.
    • Understand that searching a balanced Binary Tree is O(log n) compared to a Linked List or a completely unbalanced Binary Tree which is O(n).
  • You will probably be asked to describe the complexity of the solution you just gave (big-O notation)

See this and this for questions related to Java itself

🌐
Delft Stack
delftstack.com › home › howto › java › java iterate through a linked list
How to Iterate Through a Linked List in Java | Delft Stack
February 2, 2024 - package linkedList; import java.util.LinkedList; public class IterateLinkedListUsingForLoop { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("First"); list.add("Second"); System.out.println("Iterating the list using for-loop...
🌐
Scientech Easy
scientecheasy.com › home › blog › how to iterate linkedlist in java
How to Iterate LinkedList in Java - Scientech Easy
January 21, 2025 - The advantage of using ListIterator to traverse over a LinkedList in Java is that it offers additional methods for bidirectional iteration and modification of the list during iteration. Example 5: Let’s write a Java program where we will traverse or iterate elements of LinkedList using ListIterator.
🌐
Medium
medium.com › @AlexanderObregon › javas-linkedlist-descendingiterator-method-explained-4635fd1dbcf5
Java's LinkedList.descendingIterator() Method Explained
December 14, 2024 - The descendingIterator() method in Java's LinkedList class is a useful feature that provides an iterator to traverse a linked list in…
🌐
Crunchify
crunchify.com › java j2ee tutorials › how to iterate through linkedlist instance in java?
How to Iterate through LinkedList Instance in Java? • Crunchify
February 9, 2023 - A linked list is a data structure ... to the next node. In Java, the LinkedList class implements the Iterable interface, which provides several ways to iterate through its elements....
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › LinkedList.html
LinkedList (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable · Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null). All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
🌐
Reddit
reddit.com › r/javahelp › how do you efficiently loop through a linkedlist?
r/javahelp on Reddit: How do you efficiently loop through a linkedlist?
February 5, 2022 -

I've never come across a situation where a linkedlist would be large enough that you would need to efficiently loop through it, but I am curious how you would do it.

From my understanding, the .get method in a linkedlist has a complexity of O(n), because you begin at the first element and follow the list until you reach the nth element.

So getting the 1st element would take 1 operation, getting the 2nd element would take 2 operations, etc.

It would look something like this

LinkedList<Character> myList = new LinkedList<Character>();

myList.add(1);
myList.add(2);
myList.add(3);
// { 1, 2, 3 }

for(int i = 0; i < myList.size(); i++) {
    System.out.println(myList.get(i);
}

If I were to loop through a linkedlist in order, from element 0 to n, is there a better way to loop through a linkedlist where I just pick up where I left off, instead of starting from the beginning of the linkedlist everytime I try to get the next element? Or

🌐
Java Master
javamaster.guru › home › how to traverse a linked list in java
How to Traverse a Linked List in Java - Java Master
April 12, 2023 - There are two common ways to traverse a linked list in Java: using a while loop and using recursion.
🌐
Quora
quora.com › How-can-we-efficiently-traverse-a-linked-list
How can we efficiently traverse a linked list? - Quora
Answer (1 of 2): If you don’t have any other structure associated therewith, you need to follow a trail of pointers (or references)… Or, you can pick a language that already does that under the hood on your behalf, and use the fun features built in like map, filter, and reduce.
🌐
Software Testing Help
softwaretestinghelp.com › home › java › linked list in java – linked list implementation & java examples
Linked List In Java – Linked List Implementation & Java Examples
April 1, 2025 - In the above program, we have a linked list class created to remove duplicates. We also have a class to define each node. In other words, the nodes in the list are the objects of this class node. We have a method to add the node to a linked list. Then in the removeDuplicate method, we traverse through each node in the linked list starting from the head and compare each subsequent node for the duplicate.