Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print reverse of a Linked List without extra space and modification in C Program.
The task is to print the nodes of a linked list in reverse order without using extra space and without modifying the original linked list. This approach maintains O(1) space complexity by counting nodes and accessing them by position rather than using recursion or additional data structures.
Syntax
void printReverse(struct node* head); int getLength(struct node* head); int getNodeAtPosition(struct node* head, int position);
Algorithm
The approach involves two main steps −
- Count the total nodes in the linked list
- Print nodes by accessing them from last position to first position
Example
This program demonstrates how to print a linked list in reverse order without extra space −
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
void push(struct node** headref, int newdata) {
struct node* newnode = (struct node*) malloc(sizeof(struct node));
newnode->data = newdata;
newnode->next = (*headref);
(*headref) = newnode;
}
int getLength(struct node* head) {
int count = 0;
struct node* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
int getNodeAtPosition(struct node* head, int position) {
struct node* current = head;
for (int i = 0; i < position - 1 && current != NULL; i++) {
current = current->next;
}
return current->data;
}
void printReverse(struct node* head) {
int length = getLength(head);
for (int i = length; i >= 1; i--) {
printf("%d ", getNodeAtPosition(head, i));
}
printf("<br>");
}
int main() {
struct node* head = NULL;
push(&head, 89);
push(&head, 42);
push(&head, 33);
push(&head, 21);
push(&head, 10);
printf("Original list: 10 21 33 42 89<br>");
printf("Reverse print: ");
printReverse(head);
return 0;
}
Original list: 10 21 33 42 89 Reverse print: 89 42 33 21 10
How It Works
- Count nodes: First pass through the list counts total nodes (n)
- Access by position: Loop from position n to 1, accessing each node
- Print in reverse: Nodes are printed from last to first without modification
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time Complexity | O(n²) | For each of n positions, traverse up to n nodes |
| Space Complexity | O(1) | Only uses constant extra space |
Conclusion
This approach successfully prints a linked list in reverse order using O(1) space complexity without modifying the original structure. While the time complexity is O(n²), it achieves the goal of minimal space usage for scenarios where memory constraints are more critical than time efficiency.
