Traversing a singly linked list means visiting each node exactly once, starting at the head and following the next references until you reach null. Printing, counting, summing and searching a list are all built on traversal, and each takes O(n) time for n nodes.
There are two ways to write it:
- Iterative Approach
- Recursive Approach
Traverse a linked list using Iterative approach
A loop moves a current reference from node to node. It needs only O(1) extra memory, so it works for lists of any length.
// Java program to traverse a linked list using Iterative approach
public class TraversalUsingIterativeApproachInSLL {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
// Method to traverse and print the list
static void traverseList(Node head) {
Node current = head;
while (current != null) {
// Printing data of node
System.out.print(current.data + " -> ");
// Moving to the next node
current = current.next;
}
System.out.println("null");
}
public static void main(String[] args) {
// Create a linked list
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
// Linked list will be created like this
// 10 -> 20 -> 30 -> 40 -> 50
// Traversing and printing the list
traverseList(head);
}
}
10 -> 20 -> 30 -> 40 -> 50 -> null
Traverse a linked list using Recursive approach
The method handles one node and then calls itself on the rest of the list; an empty list (null) is the base case. Each call adds a stack frame, so it uses O(n) stack space and can throw StackOverflowError on very long lists.
// Java program to traverse a linked list using Recursive approach
public class TraversalUsingRecursiveApproachInSLL {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
// Method to traverse and print the linked list
static void traverseList(Node head) {
// Returns if list is empty
if (head == null) {
System.out.println("null");
return;
}
// Printing the node data
System.out.print(head.data + " -> ");
// Moving to the next node
traverseList(head.next);
}
public static void main(String[] args) {
// Create a linked list
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
// Linked list will be created like this
// 10 -> 20 -> 30 -> 40 -> 50
// Traversing and printing the list
traverseList(head);
}
}
10 -> 20 -> 30 -> 40 -> 50 -> null