File tree Expand file tree Collapse file tree
Linear_Data_Structures/01_Stack Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 ("\n Postfix 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+ */
You can’t perform that action at this time.
0 commit comments