반응형

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#region Question 3.6 | |
/* | |
* 큰 값이 위로 오도록 스택을 오름차순 정렬하는 프로그램을 작성하라. | |
* 여벌 스택은 하나까지만 사용할 수 있고, 스택에 보관된 요소를 배열 등의 다른 자료구조로는 복사할 수 없다. | |
* 스택은 push, pop, peek, isEmpty의 네 가지 연산을 제공한다. | |
*/ | |
public static Stack<int> Q6_Sort(Stack<int> stack) | |
{ | |
var sortedStack = new Stack<int>(); | |
while(stack.Count != 0) | |
{ | |
var t = stack.Pop(); | |
while (sortedStack.Count != 0 && sortedStack.Peek() > t) | |
{ | |
stack.Push(sortedStack.Pop()); | |
} | |
sortedStack.Push(t); | |
} | |
return sortedStack; | |
} | |
#endregion |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public void Q3_6() | |
{ | |
var stack = new Stack<int>(); | |
stack.Push(3); | |
stack.Push(4); | |
stack.Push(2); | |
stack.Push(5); | |
stack.Push(1); | |
var sortedStack = StackQueue.Q6_Sort(stack); | |
Assert.AreEqual(5, sortedStack.Pop()); | |
Assert.AreEqual(4, sortedStack.Pop()); | |
Assert.AreEqual(3, sortedStack.Pop()); | |
Assert.AreEqual(2, sortedStack.Pop()); | |
Assert.AreEqual(1, sortedStack.Pop()); | |
} |
반응형
'Develop > 코딩인터뷰' 카테고리의 다른 글
[코딩인터뷰] 문제 8.7 (0) | 2020.04.04 |
---|---|
[코딩인터뷰] 문제 3.7 (0) | 2020.04.03 |
[코딩인터뷰] 문제 3.5 (0) | 2020.04.03 |
[코딩인터뷰] 문제 3.4 (0) | 2020.04.03 |
[코딩인터뷰] 문제 3.3 (0) | 2020.04.03 |
꾸준히 노력하는 개발자 "김예건" 입니다.