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 :

Iterative
Recursive
Time Complexity : O(n) No extra space
Time complexity : O(n) Internal stack of size n+1 is used.
Contributed by Nitin Ranganath