class App
{
public App()
{
ReversePolishNotation rpn = new ReversePolishNotation();
int result = rpn.Calc("35+42+*");
Console.WriteLine("=============== {0}", result); //48
rpn = new ReversePolishNotation();
result = rpn.Calc("35+");
Console.WriteLine("=============== {0}", result); //8
rpn = new ReversePolishNotation();
result = rpn.Calc("35*");
Console.WriteLine("=============== {0}", result); //15
}
}
class ReversePolishNotation
{
Stack stack = new Stack();
public int Calc(string value)
{
foreach(char n in value)
{
if (Char.IsNumber(n))
{
stack.Push((int)Char.GetNumericValue(n));
}
else if(n == '+')
{
int a = stack.Pop();
int b = stack.Pop();
stack.Push(a + b);
}
else if (n == '*')
{
int a = stack.Pop();
int b = stack.Pop();
stack.Push(a * b);
}
}
return stack.Pop();
}
}
class Stack
{
// nested class 중첩 클래스
private class Node
{
public int Data
{
get;
private set;
}
public Node Next { get; set; }
public Node(int data)
{
this.Data = data;
}
}
private Node top;
private int count;
public Stack()
{
Console.WriteLine("스택이 생성되었습니다.");
}
public int Peek()
{
if (top == null) throw new InvalidOperationException();
return top.Data;
}
public int Count()
{
return count;
}
public int Pop()
{
count--;
int value = top.Data;
Console.WriteLine("Pop: {0} 제거", value);
Node temp = top.Next;
top = null;
top = temp;
return value;
}
public void Print()
{
if (top == null)
{
return;
}
else
{
Console.WriteLine("현재 Node의 data: {0}", top.Data);
}
if (top.Next != null)
{
Print(top.Next);
}
}
private void Print(Node next)
{
Console.WriteLine("현재 Node의 data: {0}", next.Data);
if (next.Next != null)
{
Print(next.Next);
}
}
public void Push(int value)
{
count++;
if (top == null)
{
top = new Node(value);
Console.WriteLine("stack에 {0}이 추가 되었습니다.", value);
}
else
{
Node temp = top;
top = new Node(value);
top.Next = temp;
Console.WriteLine("stack에 {0}이 새로 추가 되었습니다.", value);
}
}
public bool IsEmpty()
{
if (this.top == null)
{
return true;
}
else
{
return false;
}
}
}