Skip to content

Commit 1f87348

Browse files
authored
Merge pull request mayankgb2#22 from AksHaYGuPTa28/patch-2
String reversal using stack
2 parents b9a3f49 + d893486 commit 1f87348

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

stringreverseusingstack.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
Live Demo
2+
import java.io.IOException;
3+
4+
public class StringReverserThroughStack {
5+
private String input;
6+
private String output;
7+
public StringReverserThroughStack(String in) {
8+
input = in;
9+
}
10+
public String doRev() {
11+
int stackSize = input.length();
12+
Stack theStack = new Stack(stackSize);
13+
14+
for (int i = 0; i < input.length(); i++) {
15+
char ch = input.charAt(i);
16+
theStack.push(ch);
17+
}
18+
output = "";
19+
while (!theStack.isEmpty()) {
20+
char ch = theStack.pop();
21+
output = output + ch;
22+
}
23+
return output;
24+
}
25+
public static void main(String[] args) throws IOException {
26+
String input = "Java Source and Support";
27+
String output;
28+
StringReverserThroughStack theReverser =
29+
new StringReverserThroughStack(input);
30+
output = theReverser.doRev();
31+
System.out.println("Reversed: " + output);
32+
}
33+
class Stack {
34+
private int maxSize;
35+
private char[] stackArray;
36+
private int top;
37+
38+
public Stack(int max) {
39+
maxSize = max;
40+
stackArray = new char[maxSize];
41+
top = -1;
42+
}
43+
public void push(char j) {
44+
stackArray[++top] = j;
45+
}
46+
public char pop() {
47+
return stackArray[top--];
48+
}
49+
public char peek() {
50+
return stackArray[top];
51+
}
52+
public boolean isEmpty() {
53+
return (top == -1);
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)