Traversal of Singly Linked List is one of the fundamental operations, where we traverse or visit each node of the linked list. In this article, we will cover how to traverse all the nodes of a singly linked list along with its implementation.
Examples:
Input:
Output: 1 -> 2 -> 3 -> 4 -> 5 Explanation: Every element of each node from head node to last node is printed which means we have traversed each node successfully.
Input:
Output: 10 -> 20 -> 30 -> 40 -> 50 Explanation: Every element of each node from head node to last node is printed which means we have traversed each node successfully.
Traversal of Singly Linked List (Iterative Approach)
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 points towards the null.
Step-by-Step Algorithm:
We will initialize a temporary pointer to the head node of the singly linked list.
After that, we will check if that pointer is null or not null, if it is null, then return.
While the pointer is not null, we will access and print the data of the current node, then we move the pointer to next node.
C++
#include<iostream>usingnamespacestd;// a linked list nodeclassNode{public:intdata;Node*next;// constructor to initialize a new node with dataNode(intnew_data){this->data=new_data;this->next=nullptr;}};// function to traverse and print the singly linked listvoidtraverseList(Node*head){while(head!=nullptr){cout<<head->data;if(head->next!=nullptr)cout<<" -> ";head=head->next;}cout<<endl;}intmain(){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Node*head=newNode(10);head->next=newNode(20);head->next->next=newNode(30);head->next->next->next=newNode(40);traverseList(head);return0;}
Java
// a linked list nodeclassNode{intdata;Nodenext;// constructor to initialize a new node with dataNode(intnew_data){this.data=new_data;this.next=null;}}publicclassGfG{// function to traverse and print the singly linked listpublicstaticvoidtraverseList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" -> ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);traverseList(head);}}
Python
# a linked list nodeclassNode:# constructor to initialize a new node with datadef__init__(self,new_data):self.data=new_dataself.next=None# function to traverse and print the singly linked listdeftraverseList(head):whileheadisnotNone:print(head.data,end="")ifhead.nextisnotNone:print(" -> ",end="")head=head.nextprint()if__name__=="__main__":# create a hard-coded linked list:# 10 -> 20 -> 30 -> 40head=Node(10)head.next=Node(20)head.next.next=Node(30)head.next.next.next=Node(40)traverseList(head)
C#
usingSystem;// a linked list nodeclassNode{publicintData{get;set;}publicNodeNext{get;set;}// constructor to initialize a new node with datapublicNode(intnew_data){Data=new_data;Next=null;}}classGfG{// function to traverse and print the singly linked liststaticvoidTraverseList(Nodehead){while(head!=null){Console.Write(head.Data);if(head.Next!=null){Console.Write(" -> ");}head=head.Next;}Console.WriteLine();}publicstaticvoidMain(string[]args){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.Next=newNode(20);head.Next.Next=newNode(30);head.Next.Next.Next=newNode(40);TraverseList(head);}}
JavaScript
// a linked list nodeclassNode{// constructor to initialize a new node with dataconstructor(newData){this.data=newData;this.next=null;}}// function to traverse and print the singly linked listfunctiontraverseList(head){while(head!==null){process.stdout.write(head.data.toString());if(head.next!==null){process.stdout.write(" -> ");}head=head.next;}console.log();}// Driver code// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40lethead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);traverseList(head);
Output
10 -> 20 -> 30 -> 40
Time Complexity: O(n), where nis the number of nodes in the linked list. Auxiliary Space: O(1)
Traversal of Singly Linked List (Recursive Approach)
We can also traverse the singly linked list using recursion. We start at the head node of the singly linked list, check if it is null or not and print its value. We then call the traversal function again with the next node passed as pointer.
Step-by-Step Algorithm:
Firstly, we define a recursive method to traverse the singly linked list, which takes a node as a parameter.
In this function, the base case is that if the node is null then we will return from the recursive method.
We then pass the head node as the parameter to this function.
After that, we access and print the data of the current node.
At last, we will make a recursive call to this function with the next node as the parameter.
C++
#include<iostream>usingnamespacestd;// a linked list nodeclassNode{public:intdata;Node*next;// constructor to initialize a new node with dataNode(intnew_data){this->data=new_data;this->next=nullptr;}};// function to traverse and print the singly linked list (recursive)voidtraverseList(Node*head){// base condition is when the head is nullptrif(head==nullptr){cout<<endl;return;}// printing the current node datacout<<head->data;// print arrow if not the last nodeif(head->next!=nullptr){cout<<" -> ";}// moving to the next nodetraverseList(head->next);}intmain(){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Node*head=newNode(10);head->next=newNode(20);head->next->next=newNode(30);head->next->next->next=newNode(40);traverseList(head);return0;}
Java
// a linked list nodeclassNode{intdata;Nodenext;// constructor to initialize a new node with dataNode(intnew_data){data=new_data;next=null;}}publicclassGfG{// function to traverse and print the singly linked liststaticvoidtraverseList(Nodehead){// base condition is when the head is nullif(head==null){System.out.println();return;}// printing the current node dataSystem.out.print(head.data);// print arrow if not the last nodeif(head.next!=null){System.out.print(" -> ");}// moving to the next nodetraverseList(head.next);}publicstaticvoidmain(String[]args){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);traverseList(head);}}
Python
# a linked list nodeclassNode:def__init__(self,data):# constructor to initialize a new node with dataself.data=dataself.next=None# function to traverse and print the singly linked listdeftraverseList(head):# base condition is when the head is NoneifheadisNone:print()return# printing the current node dataprint(head.data,end="")# print arrow if not the last nodeifhead.nextisnotNone:print(" -> ",end="")# moving to the next nodetraverseList(head.next)if__name__=="__main__":# create a hard-coded linked list:# 10 -> 20 -> 30 -> 40head=Node(10)head.next=Node(20)head.next.next=Node(30)head.next.next.next=Node(40)traverseList(head)
C#
usingSystem;// a linked list nodeclassNode{publicintData{get;set;}publicNodeNext{get;set;}// constructor to initialize a new node with datapublicNode(intnewData){Data=newData;Next=null;}}classGfG{// function to traverse and print the singly linked liststaticvoidtraverseList(Nodehead){// base condition is when the head is nullif(head==null){Console.WriteLine();return;}// printing the current node dataConsole.Write(head.Data);// print arrow if not the last nodeif(head.Next!=null){Console.Write(" -> ");}// moving to the next nodetraverseList(head.Next);}staticvoidMain(){// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.Next=newNode(20);head.Next.Next=newNode(30);head.Next.Next.Next=newNode(40);traverseList(head);}}
JavaScript
// a linked list nodeclassNode{// constructor to initialize a new node with dataconstructor(new_data){this.data=new_data;this.next=null;}}// function to traverse and print the singly linked listfunctiontraverseList(head){// base condition is when the head is nullif(head===null){console.log();return;}// printing the current node dataprocess.stdout.write(head.data.toString());// print arrow if not the last nodeif(head.next!==null){process.stdout.write(" -> ");}// moving to the next nodetraverseList(head.next);}// Driver code// create a hard-coded linked list:// 10 -> 20 -> 30 -> 40lethead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);// Example of traversing the node and printingtraverseList(head);
Output
10 20 30 40
Time Complexity: O(n), where nis number of nodes in the linked list. Auxiliary Space: O(n) because of recursive stack space.