class App
{
public App()
{
Stack stack = new Stack();
stack.Push(3);
stack.Push(5);
stack.Push(7);
stack.Push(9);
Console.WriteLine();
Console.WriteLine("Count: {0}", stack.Count());
Console.WriteLine("Pop: {0}", stack.Pop());
Console.WriteLine("Peek: {0}", stack.Peek());
Console.WriteLine("Pop: {0}", stack.Pop());
Console.WriteLine("Count: {0}", stack.Count());
}
}
class Stack
{
private class Node
{
public int Data
{
get;
private set;
}
public Node Next;
public Node(int data)
{
this.Data = data;
}
}
private Node top;
private int count;
public Stack()
{
Console.WriteLine("스택이 생성되었습니다.");
}
public int Count()
{
return count;
}
public int Peek()
{
try
{
return top.Data;
}
catch
{
throw new InvalidOperationException("Peek: Stack이 비어있습니다.");
}
}
public void Push(int value)
{
count++;
if(top == null)
{
top = new Node(value);
Console.WriteLine("{0} 추가", value);
}
else
{
Node temp = top;
top = new Node(value);
top.Next = temp;
Console.WriteLine("{0} 추가", value);
}
}
public int Pop()
{
try
{
count--;
int value = top.Data;
Node temp = top.Next;
top = null;
top = temp;
return value;
}
catch
{
throw new InvalidOperationException("Pop: Stack이 비어있습니다.");
}
}
}

'C# > 수업 내용' 카테고리의 다른 글
| [C#] Queue 복습 (0) | 2021.09.24 |
|---|---|
| [C#] Queue (0) | 2021.09.23 |
| [C#] 2021-09-17 역폴란드 표기법 (0) | 2021.09.18 |
| [C#] Stack을 Linked List로 구현하기 (0) | 2021.09.17 |
| [C#] 재귀함수 (0) | 2021.09.16 |