FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/DataStructures/Stacks/InfixToPostfix.java at master · debugmm/Java · GitHub
debugmm
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
DataStructures
/
Stacks
/
InfixToPostfix.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
55 lines (51 loc) · 1.47 KB
Breadcrumbs
Java
/
DataStructures
/
Stacks
/
InfixToPostfix.java
Copy path
File metadata and controls
55 lines (51 loc) · 1.47 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
DataStructures
.
Stacks
;
import
java
.
util
.
Stack
;
public
class
InfixToPostfix
{
public
static
void
main
(
String
[]
args
)
throws
Exception
{
assert
"32+"
.
equals
(
infix2PostFix
(
"3+2"
));
assert
"123++"
.
equals
(
infix2PostFix
(
"1+(2+3)"
));
assert
"34+5*6-"
.
equals
(
infix2PostFix
(
"(3+4)*5-6"
));
}
public
static
String
infix2PostFix
(
String
infixExpression
)
throws
Exception
{
if
(!
BalancedBrackets
.
isBalanced
(
infixExpression
)) {
throw
new
Exception
(
"invalid expression"
);
}
StringBuilder
output
=
new
StringBuilder
();
Stack
<
Character
>
stack
=
new
Stack
<>();
for
(
char
element
:
infixExpression
.
toCharArray
()) {
if
(
Character
.
isLetterOrDigit
(
element
)) {
output
.
append
(
element
);
}
else
if
(
element
==
'('
) {
stack
.
push
(
element
);
}
else
if
(
element
==
')'
) {
while
(!
stack
.
isEmpty
() &&
stack
.
peek
() !=
'('
) {
output
.
append
(
stack
.
pop
());
}
stack
.
pop
();
}
else
{
while
(!
stack
.
isEmpty
() &&
precedence
(
element
) <=
precedence
(
stack
.
peek
())) {
output
.
append
(
stack
.
pop
());
}
stack
.
push
(
element
);
}
}
while
(!
stack
.
isEmpty
()) {
output
.
append
(
stack
.
pop
());
}
return
output
.
toString
();
}
private
static
int
precedence
(
char
operator
) {
switch
(
operator
) {
case
'+'
:
case
'-'
:
return
0
;
case
'*'
:
case
'/'
:
return
1
;
case
'^'
:
return
2
;
default
:
return
-
1
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL