반응형
3.4 스택으로 큐
import java.util.Stack;
public class MyQueue<T> {
Stack<T> stackNewest, stackOldest;
public MyQueue() {
stackNewest = new Stack<T>();
stackOldest = new Stack<T>();
}
public int size() {
return stackNewest.size() + stackOldest.size();
}
public void add(T value) {
stackNewest.push(value);
}
private void shiftStacks() {
if (stackOldest.isEmpty()) {
while (!stackNewest.isEmpty()) {
stackOldest.push(stackNewest.pop());
}
}
}
public T peek() {
shiftStacks();
return stackOldest.peek(); // retrieve the oldest item.
}
public T remove() {
shiftStacks();
return stackOldest.pop(); // pop the oldest item.
}
}
3.5 스택 정렬
import java.util.Stack;
import CtCILibrary.AssortedMethods;
public class Question {
public static Stack<Integer> mergesort(Stack<Integer> inStack) {
if (inStack.size() <= 1) {
return inStack;
}
Stack<Integer> left = new Stack<Integer>();
Stack<Integer> right = new Stack<Integer>();
int count = 0;
while (inStack.size() != 0) {
count++;
if (count % 2 == 0) {
left.push(inStack.pop());
} else {
right.push(inStack.pop());
}
}
left = mergesort(left);
right = mergesort(right);
while (left.size() > 0 || right.size() > 0) {
if (left.size() == 0) {
inStack.push(right.pop());
} else if (right.size() == 0) {
inStack.push(left.pop());
} else if (right.peek().compareTo(left.peek()) <= 0) {
inStack.push(left.pop());
} else {
inStack.push(right.pop());
}
}
Stack<Integer> reverseStack = new Stack<Integer>();
while (inStack.size() > 0) {
reverseStack.push(inStack.pop());
}
return reverseStack;
}
public static void sort(Stack<Integer> s) {
Stack<Integer> r = new Stack<Integer>();
while(!s.isEmpty()) {
int tmp = s.pop();
while(!r.isEmpty() && r.peek() > tmp) {
s.push(r.pop());
}
r.push(tmp);
}
while (!r.isEmpty()) {
s.push(r.pop());
}
}
public static void main(String [] args) {
Stack<Integer> s = new Stack<Integer>();
for (int i = 0; i < 10; i++) {
int r = AssortedMethods.randomIntInRange(0, 1000);
s.push(r);
}
sort(s);
while(!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
반응형
'TIL > 코딩인터뷰완전분석' 카테고리의 다른 글
타입으로 쓸 수 있는 것을 구분하자 (0) | 2023.09.30 |
---|---|
[코딩인터뷰완전분석] 20일차. 수학 및 논리 퍼즐 (0) | 2023.09.28 |
[코딩인터뷰완전분석] 18일차. 비트조작 (0) | 2023.09.26 |
[코딩인터뷰완전분석] 17일차. 트리와 그래프 (0) | 2023.09.26 |
댓글