Skip to content

Commit c5d88d0

Browse files
committed
feat: infix배열을 postfix 배열로 변경하는 기능 예제 코드 구현
1 parent 7841c60 commit c5d88d0

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

yoonexample/src/main/java/stack/InfixToPostfix.java

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,53 @@
11
package stack;
22

3+
import java.util.Arrays;
4+
35
public class InfixToPostfix {
46

57
public char[] convertInputToCharArray(String input) {
68
return input.replace(" ", "").toCharArray();
79
}
810

9-
public char[] convertInfixToPostfix(char[] input) {
10-
return null;
11+
public char[] convertInfixToPostfix(char[] infixCharArray) {
12+
Stack<Character> stack = new ListStack<>();
13+
char[] postfixCharArray = new char[infixCharArray.length];
14+
15+
int idx = 0;
16+
for (char tok : infixCharArray) {
17+
if (Character.isDigit(tok)) { // tok이 숫자인지 확인
18+
postfixCharArray[idx++] = tok; // 숫자형이면 그대로 넣고, idx값을 증가시킨다.
19+
} else { // 연산자라면
20+
switch (tok) {
21+
case '(': // 여는 괄호라면
22+
stack.push(tok); // 스택에 넣는다.
23+
break;
24+
case ')': // 닫는 괄호라면
25+
while (true) { // 계속해서
26+
char popOp = stack.pop(); // 스택에서 연산자를 꺼낸다.
27+
if (popOp == '(') { // 연산자 (를 만날 때까지
28+
break;
29+
}
30+
postfixCharArray[idx++] = popOp; // 연산자를 배열에 넣는다.
31+
}
32+
break;
33+
case '+':
34+
case '-':
35+
case '*':
36+
case '/':
37+
// 사칙연산자가 들어오면, 스택이 비어있는지 확인하고, 스택이 비어있지 않다면, 맨 위의 연산자와 비교해서 스택에 있는 연산자가 연산을 먼저해야한다면
38+
while (!stack.isEmpty() && compareOperator(stack.peek(), tok) >= 0) {
39+
postfixCharArray[idx++] = stack.pop(); // 스택에서 연산자를 꺼내서 배열에 넣는다.
40+
}
41+
stack.push(tok); // 스택에 연산자를 넣는다.
42+
break;
43+
}
44+
}
45+
}
46+
while (!stack.isEmpty()) { // 스택에 남아있는 모든 연산자를 배열에 저장한다.
47+
postfixCharArray[idx++] = stack.pop();
48+
}
49+
50+
return Arrays.copyOf(postfixCharArray, idx); // 후위 연산으로 변경되면 길이가 줄어들고, 배열의 길이는 idx값과 동일하므로
1151
}
1252

1353
public int compareOperator(char op1, char op2) {

0 commit comments

Comments
 (0)