-
Notifications
You must be signed in to change notification settings - Fork 82
/
reverseastackusingrecursion.cpp
122 lines (94 loc) · 2 KB
/
reverseastackusingrecursion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// WAP to reverse a stack using recursion.
#include<stdio.h>
#include<stdlib.h>
#define bool int
struct sNode
{
char data;
struct sNode *next;
};
void push(struct sNode** top_ref,
int new_data);
int pop(struct sNode** top_ref);
bool isEmpty(struct sNode* top);
void print(struct sNode* top);
void insertAtBottom(struct sNode** top_ref,
int item)
{
if (isEmpty(*top_ref))
push(top_ref, item);
else
{
int temp = pop(top_ref);
insertAtBottom(top_ref, item);
push(top_ref, temp);
}
}
void reverse(struct sNode** top_ref)
{
if (!isEmpty(*top_ref))
{
int temp = pop(top_ref);
reverse(top_ref);
insertAtBottom(top_ref, temp);
}
}
int main()
{
struct sNode *s = NULL;
push(&s, 10);
push(&s, 79);
push(&s, 31);
push(&s, 39);
printf("\n Original Stack ");
print(s);
reverse(&s);
printf("\n Reversed Stack ");
print(s);
return 0;
}
bool isEmpty(struct sNode* top)
{
return (top == NULL)? 1 : 0;
}
void push(struct sNode** top_ref,
int new_data)
{
struct sNode* new_node =
(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow \n");
exit(0);
}
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
if (*top_ref == NULL)
{
printf("Stack overflow \n");
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
}
void print(struct sNode* top)
{
printf("\n");
while (top != NULL)
{
printf(" %d ", top->data);
top = top->next;
}
}