Displaying the Nodes

Iterative and recursive method to print all the nodes in a linked list.

Iterative Method :

void display(struct node *ptr) {
    
    // Checking if list is empty
    if (ptr == NULL) {
        printf("The list is empty\n");
    }
    // Iterate till the end otherwise
    else {
        while (ptr != NULL) {
            printf("%d\t", ptr -> data);
            ptr = ptr -> next;
        }
    }
    
}

Recursive Method :

void display(struct node *ptr) {

    if (ptr != NULL) {
        printf("%d\t", ptr -> data);
        display(ptr -> next);
    }

}

Recursive & Reversed :

void display(struct node *ptr) {

    if (ptr != NULL) {
        display(ptr -> next);
        printf("%d\t", ptr -> data);
    }

}

Time and Space Complexity :

Time Complexity : O(n) No extra space

Contributed by Nitin Ranganath

Last updated