오늘은 leetcode의 문제가 주어졌다.
leetcode는 처음 접해봐서 적응하기까지 시간이 다소 소요됐다.
leetcode는 입력과 출력 코드를 따로 작성하지 않아도 되는 장점이 있다.
스택을 큐처럼 구현하는 문제였는데 전혀 감이 잡히지 않을 정도로 어려웠다...
이번에도 역시나 다른 사람들의 코드를 보고 풀었다.🥲
[leetcode: easy 232] Implement Queue using Stacks
🐥 제출한 코드
class MyQueue {
Stack<Integer> input = new Stack<>();
Stack<Integer> output = new Stack<>();
public void push(int x) {
input.push(x);
}
public int pop() {
shiftStack();
return output.pop();
}
public int peek() {
shiftStack();
return output.peek();
}
public boolean empty() {
return input.isEmpty() && output.isEmpty();
}
private void shiftStack() {
if (output.isEmpty()) {
while (!input.isEmpty()) {
output.push(input.pop());
}
}
}
}
👨🏻💻 시니어 개발자의 코드
import java.util.Stack;
class MyQueue {
private Stack<Integer> stackIn;
private Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.pop();
}
public int peek() {
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
}'코딩테스트 > [스파르타] 작심큰일 코테 챌린지' 카테고리의 다른 글
| [Day 6] TIL (2) | 2025.08.12 |
|---|---|
| [Day 5] TIL (2) | 2025.08.08 |
| [Day 4] TIL (3) | 2025.08.07 |
| [Day 2] TIL (1) | 2025.08.05 |
| [Day 1] TIL (2) | 2025.08.04 |
