-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseStringUsingStack.java
More file actions
45 lines (35 loc) · 1016 Bytes
/
Copy pathReverseStringUsingStack.java
File metadata and controls
45 lines (35 loc) · 1016 Bytes
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
import java.util.Scanner;
public class ReverseStringUsingStack {
static final int MAX = 100;
static char[] stack = new char[MAX];
static int top = -1;
static void push(char p) {
if (top == MAX - 1) {
System.out.println("Stack Overflow");
} else {
stack[++top] = p;
}
}
static char pop() {
if (top == -1) {
System.out.println("Stack Underflow");
return '\0';
}
return stack[top--];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
int l = str.length();
char[] result = new char[l];
for (int i = 0; i < l; i++) {
push(str.charAt(i));
}
for (int i = 0; i < l; i++) {
result[i] = pop();
}
System.out.println("Reversed String is: " + new String(result));
sc.close();
}
}