This C program reverses the elements of a stack using Recursion. Here, Stack is represented using a linked list. A linked list is an ordered set of data elements, each containing a link to its successor.
Enter length of list: 20
The sequence of contents in stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Reversing the contents of the stack
The contents in stack after reversal
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Program Explanation
1. This C program comprises of four major functions. These functions are for generating stack, to display the generated stack, to reverse the stack and finally to free the memory.
2. Here stack in implemented using a linked list. Stack is simply created in the form of a list starting form 1 up to the number entered by the user.
3. The stack is reversed using the recursion. The function stack_reverse is called recursively until the next of node becomes null. The elements of the list are swapped with the next element using a temporary list.
4. Function display_stack is used to display the contents of the list at any time.
C program to reverse a stack using recursion - Source code
Program Output
Program Explanation
1. This C program comprises of four major functions. These functions are for generating stack, to display the generated stack, to reverse the stack and finally to free the memory.
2. Here stack in implemented using a linked list. Stack is simply created in the form of a list starting form 1 up to the number entered by the user.
3. The stack is reversed using the recursion. The function stack_reverse is called recursively until the next of node becomes null. The elements of the list are swapped with the next element using a temporary list.
4. Function display_stack is used to display the contents of the list at any time.
need an explanation for this answer? contact us directly to get an explanation for this answer