입력받은 스택이 있습니다.
새로운 스택을 생성하여 정렬을 진행합니다.
정렬된 스택이 결과로 출력됩니다.
public void sortedStack(Stack stack){
Stack<Integer> newStack = new Stack<>(stack.getMaxSize());
while (!stack.isEmpty()){
int value = (int) stack.pop();
if(!newStack.isEmpty() && value >= newStack.top()){
newStack.push(value);
} else {
while (!newStack.isEmpty() && newStack.top() > value){
stack.push(newStack.pop());
}
newStack.push(value);
}
}
}
@Test
public void sortedStack(){
Stack<Integer> stack = new Stack<>(6);
stack.push(1);
stack.push(100);
stack.push(10);
stack.push(1000);
stack.push(2);
stack.push(200);
sortedStack(stack);
String res = "";
while (!stack.isEmpty()){
res+=stack.pop() + " ";
}
Assert.assertEquals("1 2 10 100 200 1000 ", res);
}
[Graph] 인접행렬, 인접리스트 시간복잡도 (0) | 2020.04.16 |
---|---|
[Graph] 특징 (0) | 2020.04.14 |
[Queue] 스택을 이용한 큐 구현 (0) | 2020.04.05 |
[Queue] 기본 구현 enqueue, dequeue (0) | 2020.04.04 |
[Queue] reverse k (0) | 2020.04.04 |
댓글 영역