Traversal of Singly Linked List (original) (raw)

Last Updated : 18 Feb, 2025

Try it on GfG Practice redirect icon

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.

Traversal-of-Singly-Linked-List

**Examples:

**Input: 1->2->3->4->5->null
**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: 10->20->30->40->50->null
**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.

**Input: 5->10->15->20->25->null
**Output: 5 10 15 20 25
**Explanation: Each node's value is printed sequentially from the head to the last node, confirming successful traversal.

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:

#include

using namespace std;

// A linked list node class Node { public: int data; Node* next;

// Constructor to initialize a new node with data
Node(int new_data) {
    this->data = new_data;
    this->next = nullptr;
}

};

// Function to traverse and print the singly linked list void traverseList(Node* head) {

// A loop that runs till head is nullptr
while (head != nullptr) {

    // Printing data of current node
    cout << head->data << " ";

    // Moving to the next node
    head = head->next;
}
cout << endl;

}

// Driver Code int main() {

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node* head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
head->next->next->next = new Node(40);

// Example of traversing the node and printing
traverseList(head);

return 0;

}

C

#include <stdio.h> #include <stdlib.h>

// A linked list node struct Node { int data; struct Node* next; };

// Function to create a new node struct Node* createNode(int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = NULL; return new_node; }

// Function to traverse and print the singly linked list void traverseList(struct Node* head) {

// Loop that runs until head is NULL
while (head != NULL) {
  
    // Printing data of current node
    printf("%d ", head->data);

    // Moving to the next node
    head = head->next;
}
printf("\n");

}

// Driver code int main() {

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
struct Node* head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
head->next->next->next = createNode(40);

// Example of traversing the node and printing
traverseList(head);

return 0;

}

Java

// A linked list node class Node { int data; Node next;

// Constructor to initialize a new node with data
Node(int new_data) {
    this.data = new_data;
    this.next = null;
}

}

public class GfG {

// Function to traverse and print the singly linked list
public static void traverseList(Node head) {

    // A loop that runs till head is nullptr
    while (head != null) {

        // Printing data of current node
        System.out.print(head.data + " ");

        // Moving to the next node
        head = head.next;
    }
    System.out.println();
}

// Driver code
public static void main(String[] args) {
  
    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40
    Node head = new Node(10);
    head.next = new Node(20);
    head.next.next = new Node(30);
    head.next.next.next = new Node(40);

    // Example of traversing the node and printing
    traverseList(head);
}

}

Python

A linked list node

class Node:

# Constructor to initialize a new node with data
def __init__(self, new_data):
    self.data = new_data
    self.next = None

Function to traverse and print the singly linked list

def traverseList(head):

# A loop that runs till head is nullptr
while head is not None:

    # Printing data of current node
    print(head.data, end=" ")
    
    # Moving to the next node
    head = head.next
print()

Driver code

def main():

# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)

# Example of traversing the node and printing
traverseList(head)

if name == "main": main()

C#

using System;

// A linked list node class Node { public int Data { get;set; } public Node Next { get;set; }

// Constructor to initialize a new node with data
public Node(int new_data) {
    Data = new_data;
    Next = null;
}

}

class GfG {

// Function to traverse and print the singly linked list
static void TraverseList(Node head) {

    // A loop that runs till head is nullptr
    while (head != null) {

        // Printing data of current node
        Console.Write(head.Data + " ");

        // Moving to the next node
        head = head.Next;
    }
    Console.WriteLine();
}

// Driver Code
public static void Main(string[] args) {
  
    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40
    Node head = new Node(10);
    head.Next = new Node(20);
    head.Next.Next = new Node(30);
    head.Next.Next.Next = new Node(40);

    // Example of traversing the node and printing
    TraverseList(head);
}

}

JavaScript

// A linked list node class Node {

// Constructor to initialize a new node with data
constructor(new_data)
{
    this.data = new_data;
    this.next = null;
}

}

// Function to traverse and print the singly linked list function traverseList(head) {

// A loop that runs till head is nullptr
while (head != null) {

    // Printing data of current node
    process.stdout.write(head.data + " ");

    // Moving to the next node
    head = head.next;
}
console.log();

}

// Driver code function main() {

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);

// Example of traversing the node and printing
traverseList(head);

}

// Calling the main method to execute the code main();

`

**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:

#include

using namespace std;

// A linked list node class Node { public: int data; Node* next;

// Constructor to initialize a new node with data
Node(int new_data) {
    this->data = new_data;
    this->next = nullptr;
}

};

// Function to traverse and print the singly linked list void traverseList(Node* head) {

// Base condition is when the head is nullptr
if (head == nullptr) {
    cout << endl;
    return;
}

// Printing the current node data
cout << head->data << " ";

// Moving to the next node
traverseList(head->next);

}

// Driver code int main() {

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node* head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
head->next->next->next = new Node(40);

// Example of traversing the node and printing
traverseList(head);

return 0;

}

C

#include <stdio.h> #include <stdlib.h>

// A linked list node struct Node { int data; struct Node* next; };

// Function to create a new node with given data struct Node* createNode(int new_data) { struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = NULL; return new_node; }

// Function to traverse and print the singly linked list void traverseList(struct Node* head) {

// Base condition is when the head is nullptr
if (head == NULL) {
    printf("\n");
    return;
}

// Printing the current node data
printf("%d ", head->data);

// Moving to the next node
traverseList(head->next);

}

// Driver code int main() {

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
struct Node* head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
head->next->next->next = createNode(40);

// Example of traversing the node and printing
traverseList(head);

return 0;

}

Java

// A linked list node class Node { int data; Node next;

// Constructor to initialize a new node with data
Node(int new_data) {
    data = new_data;
    next = null;
}

}

public class GfG {

// Function to traverse and print the singly linked list
static void traverseList(Node head) {

    // Base condition is when the head is nullptr
    if (head == null) {
        System.out.println();
        return;
    }

    // Printing the current node data
    System.out.print(head.data + " ");

    // Moving to the next node
    traverseList(head.next);
}

// driver code
public static void main(String[] args) {
  
    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40
    Node head = new Node(10);
    head.next = new Node(20);
    head.next.next = new Node(30);
    head.next.next.next = new Node(40);

    // Example of traversing the node and printing
    traverseList(head);
}

}

Python

A linked list node

class Node: def init(self, data):

    # Constructor to initialize a new node with data
    self.data = data
    self.next = None

Function to traverse and print the singly linked list

def traverseList(head):

# Base condition is when the head is nullptr
if head is None:
    print()
    return
  
# Printing the current node data
print(head.data, end=" ")

# Moving to the next node
traverseList(head.next)

Driver code

def main():

# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)

# Example of traversing the node and printing
traverseList(head)

if name == "main": main()

C#

using System;

// A linked list node class Node { public int Data { get;set; } public Node Next { get;set; }

// Constructor to initialize a new node with data
public Node(int newData) {
    Data = newData;
    Next = null;
}

}

class GfG {

// Function to traverse and print the singly linked list
static void TraverseList(Node head) {
  
    // Base condition is when the head is nullptr
    if (head == null) {
        Console.WriteLine();
        return;
    }

    // Printing the current node data
    Console.Write(head.Data + " ");

    // Moving to the next node
    TraverseList(head.Next);
}

// Driver code
static void Main() {
  
    // Create a hard-coded linked list:
    // 10 -> 20 -> 30 -> 40
    Node head = new Node(10);
    head.Next = new Node(20);
    head.Next.Next = new Node(30);
    head.Next.Next.Next = new Node(40);

    // Example of traversing the node and printing
    TraverseList(head);
}

}

JavaScript

// A linked list node class Node {

// Constructor to initialize a new node with data
constructor(new_data) {
    this.data = new_data;
    this.next = null;
}

}

// Function to traverse and print the singly linked list function traverseList(head) {

// Base condition is when the head is nullptr
if (head === null) {
    console.log();
    return;
}

// Printing the current node data
process.stdout.write(head.data + " ");

// Moving to the next node
traverseList(head.next);

}

// Driver code function main() {

// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);

// Example of traversing the node and printing
traverseList(head);

}

main();

`

**Time Complexity: O(n), where nis number of nodes in the linked list.
**Auxiliary Space: O(n) because of recursive stack space.