forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixToPostfix.java
111 lines (101 loc) · 2.71 KB
/
InfixToPostfix.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
/**
* Infix to Postfix Expression
*
* This program converts an infix expression entered by the user
* into the Postfix expression.
* The program uses a stack to keep the track of the operators and
* paranthesis of the input expression.
*
* Author: iamvs-2002
*/
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.Stack;
public class InfixToPostfix
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Kindly enter the infix expression: ");
String infix = sc.nextLine();
InfixToPostfix x = new InfixToPostfix();
String postfix = x.infixtopostfix(infix);
System.out.println("Postfix Expression: "+postfix);
}
static int priority(char c)
{
switch (c)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
case '^':
return 3;
default:
return -1;
}
}
private String infixtopostfix(String expression)
{
String result = "";
Stack<Character> stack = new Stack<>();
int i=0;
for (i = 0; i < expression.length() ; i++)
{
char c = expression.charAt(i);
if(priority(c)>0)
{
//if the topmost operator in the stack has a priority greater than or equal to c
//pop it and add to result string
//else push it into the stack
while(stack.isEmpty()==false && (priority(stack.peek())>=priority(c)))
{
result = result + stack.pop();
}
stack.push(c);
}
else if(c==')')
{
//if character is ending bracket ')'
//pop from stack, until '(' is found
while(stack.peek()!='(')
{
result = result + stack.peek();
stack.pop();
}
char x = stack.pop();
}
else if(c=='(')
{
stack.push(c);
}
else
{
result = result + c;
}
}
while (!stack.isEmpty())
result = result + stack.pop();
return result;
}
}
/**
* Sample Outputs:
*
* Kindly enter the infix expression:
* (X - Y / (Z + U) * V)
* Postfix Expression: X Y Z U+ / V*-
*
* Kindly enter the infix expression:
* ab+
* Postfix Expression: ab +
*
* Time Complexity: O(n^2)
* Space Complexity: O(n)
*/