Skip to content

Commit 3cfc6be

Browse files
authored
Create StackApplications.java
1 parent 9595080 commit 3cfc6be

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// Author: Aayush Raj
2+
// Description: Demonstrates Undo simulation and postfix evaluation using Stack
3+
4+
import java.util.Stack;
5+
6+
public class StackApplications {
7+
public static int evaluatePostfix(String expr) {
8+
Stack<Integer> stack = new Stack<>();
9+
10+
for (char c : expr.toCharArray()) {
11+
if (Character.isDigit(c))
12+
stack.push(c - '0');
13+
else {
14+
int val2 = stack.pop();
15+
int val1 = stack.pop();
16+
switch (c) {
17+
case '+': stack.push(val1 + val2); break;
18+
case '-': stack.push(val1 - val2); break;
19+
case '*': stack.push(val1 * val2); break;
20+
case '/': stack.push(val1 / val2); break;
21+
}
22+
}
23+
}
24+
return stack.pop();
25+
}
26+
27+
public static void main(String[] args) {
28+
System.out.println("Undo Simulation using Stack:");
29+
Stack<String> actions = new Stack<>();
30+
actions.push("Typed 'Hello'");
31+
actions.push("Typed 'World'");
32+
System.out.println(actions.pop() + " undone!");
33+
34+
System.out.println("\nPostfix Evaluation:");
35+
String postfix = "53*2+";
36+
System.out.println("Result: " + evaluatePostfix(postfix));
37+
}
38+
}
39+
40+
/*
41+
🖥️ Output:
42+
Undo Simulation using Stack:
43+
Typed 'World' undone!
44+
45+
Postfix Evaluation:
46+
Result: 17
47+
*/

0 commit comments

Comments
 (0)