-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverse_string_using_stack.c
More file actions
101 lines (86 loc) · 1.76 KB
/
Reverse_string_using_stack.c
File metadata and controls
101 lines (86 loc) · 1.76 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
struct Stack
{
int top;
unsigned capacity;
char* array;
};
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack -> capacity = capacity;
stack -> top = -1;
stack -> array = (char*)malloc(stack -> capacity * sizeof(char));
return stack;
}
bool isFull(struct Stack*stack)
{
if(stack->top==stack->capacity-1)
return true;
return false;
}
bool isEmpty(struct Stack*stack)
{
if(stack->top==-1)
return true;
return false;
}
void push(struct Stack* stack, char ch)
{
if(isFull(stack))
return;
else
stack->array[++stack->top] = ch;
}
char pop(struct Stack* stack)
{
char ch = ' ';
if(isEmpty(stack) == false)
ch = stack->array[stack->top];
stack->array[stack->top--] = ' ';
return ch;
}
int main(void)
{
struct Stack* stack = NULL;
char *s;
s = (char*) malloc(sizeof(char)*100);
printf("Enter the string to reverse:-->");
scanf("%[^\n]s", s);
int len = strlen(s);
int size = len-1;
while(size!=0) {
if(s[size--] != 32) {
break;
}
len -= 1;
}
int i=0;
while(i<len)
{
if(s[i] != 32)
break;
i++;
}
stack = createStack(len);
int nSize = len-i;
char *ns;
ns = (char*) calloc(sizeof(char), (nSize));
for(; i<len; i++)
{
push(stack, s[i]);
}
for(i=0; i<nSize; i++)
{
ns[i] = pop(stack);
}
printf("%d %d\n", len, nSize);
printf("The Original string:\n\"%s\"\n", s);
printf("The Reversed string:\n\"%s\"\n", ns);
free(stack);
free(ns);
free(s);
}