-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPostfixEvaluation.java
88 lines (81 loc) · 2.12 KB
/
PostfixEvaluation.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
78
79
80
81
82
83
84
85
86
87
88
/*https://practice.geeksforgeeks.org/problems/evaluation-of-postfix-expression1735/1*/
/*https://leetcode.com/problems/evaluate-reverse-polish-notation/*/
class Solution
{
public static int evaluatePostFix(String S)
{
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < S.length(); ++i)
{
char ch = S.charAt(i);
if (ch >= '0' && ch <= '9') stack.push(ch-'0');
else
{
int op1 = stack.pop();
int op2 = stack.pop();
if (ch == '+') stack.push(op2+op1);
else if (ch == '-') stack.push(op2-op1);
else if (ch == '*') stack.push(op2*op1);
else if (ch == '/') stack.push(op2/op1);
}
}
return stack.pop();
}
}
/*Leetcode*/
class Node
{
int op;
Node next;
Node(int op)
{
this.op = op;
}
}
class OpStack
{
public Node top;
public void push(int str)
{
if (top == null)
top = new Node(str);
else
{
Node newNode = new Node(str);
newNode.next = top;
top = newNode;
}
}
public int pop()
{
if (top == null)
throw new NullPointerException("Stack is Empty");
Node returnNode = top;
top = top.next;
return returnNode.op;
}
}
class Solution {
public int evalRPN(String[] tokens) {
OpStack stack = new OpStack();
for (int i = 0; i < tokens.length; ++i)
{
if (!tokens[i].equals("+") && !tokens[i].equals("-") && !tokens[i].equals("*") && !tokens[i].equals("/"))
stack.push(Integer.parseInt(tokens[i]));
else
{
int op1 = stack.pop();
int op2 = stack.pop();
if (tokens[i].equals("+"))
stack.push(op2+op1);
else if (tokens[i].equals("-"))
stack.push(op2-op1);
else if (tokens[i].equals("*"))
stack.push(op2*op1);
else if (tokens[i].equals("/"))
stack.push(op2/op1);
}
}
return stack.pop();
}
}