-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDemo.java
133 lines (114 loc) · 2.33 KB
/
Demo.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
package postfix;
import java.util.Scanner;
public class Demo
{
public static void main(String[] args)
{
String infix;
Scanner scan = new Scanner(System.in);
System.out.print("Enter infix expression : ");
infix = scan.nextLine();
String postfix = infixToPostfix(infix);
System.out.println("Postfix expression is : " + postfix);
System.out.println("Value of expression : " + evaluatePostfix(postfix));
scan.close();
}
public static String infixToPostfix(String infix)
{
String postfix = new String();
StackChar st = new StackChar(20);
char next,symbol;
for(int i=0; i<infix.length(); i++)
{
symbol=infix.charAt(i);
if(symbol==' ' || symbol=='\t') /*ignore blanks and tabs*/
continue;
switch(symbol)
{
case '(':
st.push(symbol);
break;
case ')':
while((next=st.pop())!='(')
postfix = postfix + next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while( !st.isEmpty() && precedence(st.peek())>= precedence(symbol) )
postfix = postfix + st.pop();
st.push(symbol);
break;
default: /*operand*/
postfix = postfix + symbol;
}
}
while(!st.isEmpty())
postfix = postfix + st.pop();
return postfix;
}
public static int precedence(char symbol)
{
switch(symbol)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default :
return 0;
}
}
public static int evaluatePostfix(String postfix)
{
StackInt st = new StackInt(20);
int x,y;
for(int i=0; i<postfix.length(); i++)
{
if(Character.isDigit(postfix.charAt(i)))
st.push(Character.getNumericValue(postfix.charAt(i)));
else
{
x=st.pop();
y=st.pop();
switch(postfix.charAt(i))
{
case '+':
st.push(y+x); break;
case '-':
st.push(y-x); break;
case '*':
st.push(y*x); break;
case '/':
st.push(y/x); break;
case '%':
st.push(y%x); break;
case '^':
st.push(power(y,x));
}
}
}
return st.pop();
}
public static int power(int b,int a)
{
int i,x=1;
for(i=1; i<=a; i++)
x=x*b;
return x;
}
}