forked from tejaswini264/Easy_DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringReversalUsingStack_Mruganka.cpp
117 lines (93 loc) · 2.18 KB
/
StringReversalUsingStack_Mruganka.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
/*Given an array arr[] of size N, the task to reverse the array using Stack.*/
// C program to implement
// the above approach
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Structure of stack
struct Stack {
// Stores index of top
// element of a stack
int top;
// Stores maximum count of
// elements stored in a stack
unsigned capacity;
// Stores address of
// array element
int* array;
};
// Function to Initialize a stack
// of given capacity.
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack
= (struct Stack*)malloc(
sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array
= (int*)malloc(
stack->capacity
* sizeof(int));
return stack;
}
// Function to check if
// the stack is full or not
int isFull(struct Stack* stack)
{
return stack->top
== stack->capacity - 1;
}
// Function to check if
// the stack is empty or not
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
// Function to insert an element
// into the stack.
void push(struct Stack* stack, int item)
{
// If stack is full
if (isFull(stack))
return;
// Insert element into stack
stack->array[++stack->top] = item;
}
// Function to remove an element
// from stack.
int pop(struct Stack* stack)
{
// If stack is empty
if (isEmpty(stack))
return -1;
// Pop element from stack
return stack->array[stack->top--];
}
// Function to reverse the array elements
void reverseArray(int arr[], int n)
{
// Initialize a stack of capacity n
struct Stack* stack = createStack(n);
for (int i = 0; i < n; i++) {
// Insert arr[i] into the stack
push(stack, arr[i]);
}
// Reverse the array elements
for (int i = 0; i < n; i++) {
// Update arr[i]
arr[i] = pop(stack);
}
// Print array elements
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}
// Driver Code
int main()
{
int arr[] = { 100, 200, 300, 400 };
int N = sizeof(arr) / sizeof(arr[0]);
reverseArray(arr, N);
return 0;
}