-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathPrefix_to_postfix.java
60 lines (52 loc) · 1.77 KB
/
Prefix_to_postfix.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
/*
An expression is called prefix , if the operator appears in the expression before the operands. (operator operand operand)
An expression is called postfix , if the operator appears in the expression after the operands . (operand operand operator)
The program below accepts an expression in prefix and outputs the corresponding postfix expression .
*/
import java.util.Scanner;
import java.util.Stack;
class Code2 {
// if operand function checks if the element is an operand
static boolean ifoperand(char c) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
return true;
}
return false;
}
// prefixtopostfix function converts a prefix expression to postfix
static void prefixtopostfix(String expression) {
Stack<String> s = new Stack<String>();
int len = expression.length();
for (int i = len - 1; i >= 0; i--) {
if (ifoperand(expression.charAt(i))) {
s.push("" + expression.charAt(i));
} else {
String exp = "" + expression.charAt(i);
String op1 = s.peek();
s.pop();
String op2 = s.peek();
s.pop();
String temp = op1 + op2 + exp;
s.push(temp);
}
}
System.out.println("the postfix expresssion is : " + s.peek());
}
// Driver code
public static void main(String[] args) {
String exp;
System.out.println("Enter the prefix expression ");
Scanner sc = new Scanner(System.in);
exp = sc.nextLine();
prefixtopostfix(exp);
sc.close();
}
}
/*
Sample I/O:
Enter the prefix expression
*+abc
the postfix expresssion is : ab+c*
Time complexity : O(n)
space complexity : O (n)
*/