반응형

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.2 | |
/* | |
* push와 pop의 두가지 연산뿐 아니라, 최솟값을 갖는 원소를 반환하는 min 연산을 갖춘 스택은 어떻게 구현할 수 있겠는가? | |
*/ | |
public class StackWithMin | |
{ | |
/// <summary> | |
/// 데이터를 저장하는 스택 | |
/// </summary> | |
private Stack<int> dataStack; | |
/// <summary> | |
/// 최솟값을 저장하는 스택 | |
/// </summary> | |
private Stack<int> minStack; | |
/// <summary> | |
/// 스택 최솟값 | |
/// </summary> | |
public int Min | |
{ | |
get | |
{ | |
try | |
{ | |
return minStack.Peek(); | |
} | |
catch (InvalidOperationException) | |
{ | |
return int.MaxValue; | |
} | |
} | |
} | |
/// <summary> | |
/// 클래스 초기화 | |
/// </summary> | |
public StackWithMin() | |
{ | |
this.minStack = new Stack<int>(); | |
this.dataStack = new Stack<int>(); | |
} | |
/// <summary> | |
/// 입력된 <paramref name="value"/> 데이터를 저장한다. | |
/// </summary> | |
/// <param name="value">저장할 데이터</param> | |
public void Push(int value) | |
{ | |
// 새로 입력된 데이터가 현재 최솟값보다 작은지 확인한다. | |
if (value <= Min) | |
{ | |
this.minStack.Push(value); | |
} | |
this.dataStack.Push(value); | |
} | |
/// <summary> | |
/// 스택에서 마지막으로 저장된 데이터를 반환한다. | |
/// </summary> | |
/// <returns>스택 최상단 데이터</returns> | |
public int Pop() | |
{ | |
try | |
{ | |
var value = this.dataStack.Pop(); | |
// 만약 최솟값과 반환할 데이터가 같을 경우, 이전 최솟값으로 변경한다. | |
if (value == Min) | |
{ | |
this.minStack.Pop(); | |
} | |
return value; | |
} | |
catch (InvalidOperationException) | |
{ | |
throw new Exception("Stack is empty."); | |
} | |
} | |
} | |
#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_2() | |
{ | |
var stackWithMin = new StackQueue.StackWithMin(); | |
stackWithMin.Push(6); | |
stackWithMin.Push(3); | |
stackWithMin.Push(8); | |
Assert.AreEqual(3, stackWithMin.Min); | |
Assert.AreEqual(8, stackWithMin.Pop()); | |
Assert.AreEqual(3, stackWithMin.Pop()); | |
Assert.AreEqual(6, stackWithMin.Min); | |
Assert.AreEqual(6, stackWithMin.Pop()); | |
} |
반응형
'Develop > 코딩인터뷰' 카테고리의 다른 글
[코딩인터뷰] 문제 3.4 (0) | 2020.04.03 |
---|---|
[코딩인터뷰] 문제 3.3 (0) | 2020.04.03 |
[코딩인터뷰] 문제 3.1 (0) | 2020.04.03 |
[코딩인터뷰] 문제 2.7 (0) | 2020.04.03 |
[코딩인터뷰] 문제 2.6 (0) | 2020.04.03 |
꾸준히 노력하는 개발자 "김예건" 입니다.