-
Notifications
You must be signed in to change notification settings - Fork 0
/
String_Reverser.java
77 lines (68 loc) · 1.28 KB
/
String_Reverser.java
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
//string reverser using stack
import java.util.*;
class Stack
{
int size;
int top;
char arr[];
boolean Empty()
{
return (top<0);
}
Stack(int n)
{
size = n;
top=-1;
arr = new char[size];
}
void push(char e)
{
if(top>=size)
{
System.out.println("Stack is full!!");
//return false;
}
else
{
arr[++top] = e ;
//return true;
}
}
char pop()
{
if(top==-1)
{
System.out.println("Stack is empty!!");
return 0;
}
else
{
char re = arr[top];
top--;
return re;
}
}
}
public class Reverser
{
public static void reverse(StringBuffer str)
{
Stack obj = new Stack(str.length());
for(int i=0; i<str.length(); i++)
{
obj.push(str.charAt(i));
}
for(int j=0; j<str.length();j++)
{
char ch= obj.pop();
str.setCharAt(j, ch);
//the element being popped out from the top of stack is being set at the 0 and increasing index
}
}
public static void main(String args[])
{
StringBuffer s = new StringBuffer("Anything to REverse");
reverse(s);
System.out.println("The reversed String is "+s);
}
}