-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReversing string using stack
77 lines (61 loc) · 1.28 KB
/
Reversing string using stack
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
#include <bits/stdc++.h>
using namespace std;
// A structure to represent a stack
class Stack {
public:
int top;
unsigned capacity;
char* array;
};
Stack* createStack(unsigned capacity)
{
Stack* stack = new Stack();
stack->capacity = capacity;
stack->top = -1;
stack->array
= new char[(stack->capacity * sizeof(char))];
return stack;
}
// Stack is full when top is equal to the last index
int isFull(Stack* stack)
{
return stack->top == stack->capacity - 1;
}
// Stack is empty when top is equal to -1
int isEmpty(Stack* stack) { return stack->top == -1; }
// Function to add an item to stack.
// It increases top by 1
void push(Stack* stack, char item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
}
char pop(Stack* stack)
{
if (isEmpty(stack))
return -1;
return stack->array[stack->top--];
}
// A stack based function to reverse a string
void reverse(char str[])
{
// Create a stack of capacity
// equal to length of string
int n = strlen(str);
Stack* stack = createStack(n);
// Push all characters of string to stack
int i;
for (i = 0; i < n; i++)
push(stack, str[i]);
for (i = 0; i < n; i++)
str[i] = pop(stack);
}
// Driver code
int main()
{
char str[] = "GeeksQuiz";
reverse(str);
cout << "Reversed string is " << str;
return 0;
}