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
Selected Reading
Print Reverse a linked list using Stack
Given a linked list, the program must print the list starting from the end till the front using the stack data structure. This approach leverages the LIFO (Last In First Out) property of stacks to reverse the order of elements.
Input : 10 -> 5 -> 3 -> 1 -> 7 -> 9 Output: 9 -> 7 -> 1 -> 3 -> 5 -> 10
Syntax
struct Node {
int data;
struct Node* next;
};
// Stack operations
void push_to_stack(int stack[], int* top, int value);
int pop_from_stack(int stack[], int* top);
Algorithm
START
Step 1 -> Create structure Node
Declare int data
Declare struct Node *next
End
Step 2 -> Declare int stack[30], top = -1
Step 3 -> Declare struct Node* head = NULL
Step 4 -> Create function printFromStack(int stack[])
Loop While top >= 0
Print stack[top--]
End
Step 5 -> Create function push(struct Node** head, int n)
Create newnode and allocate memory
Set newnode->data = n
Set newnode->next = (*head)
Set (*head) = newnode
Step 6 -> Create function intoStack(struct Node* head)
Loop While head != NULL
Push head->data to stack
Set head = head->next
End
Step 7 -> In main()
Create linked list nodes
Call intoStack(head)
Call printFromStack(stack)
STOP
Example
This example demonstrates how to use a stack to print a linked list in reverse order −
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
int stack[30], top = -1;
struct Node* head = NULL;
void printFromStack() {
printf("\nReversed linked list using stack:
");
while(top >= 0) {
printf("%d ", stack[top--]);
}
printf("
");
}
void push(struct Node** head, int n) {
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data = n;
newnode->next = (*head);
(*head) = newnode;
}
void intoStack(struct Node* head) {
printf("Original linked list:
");
while(head != NULL) {
printf("%d ", head->data);
stack[++top] = head->data;
head = head->next;
}
printf("
");
}
int main() {
push(&head, 10);
push(&head, 20);
push(&head, 30);
push(&head, 40);
intoStack(head);
printFromStack();
return 0;
}
Original linked list: 40 30 20 10 Reversed linked list using stack: 10 20 30 40
How It Works
- Traverse the linked list from head to tail and push each element onto the stack.
- Pop elements from stack one by one, which gives the reverse order due to LIFO property.
- Time complexity: O(n) for traversal + O(n) for printing = O(n)
- Space complexity: O(n) for the stack storage
Conclusion
Using a stack to print a linked list in reverse is an efficient approach that leverages the LIFO property. This method is simple to implement and has linear time complexity, making it suitable for moderate-sized linked lists.
Advertisements
