代码随笔。。。。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StackGetMinValues
{
public class Program
{
public void Main(string[] args)
{
MyStack myStack = new MyStack();
myStack.Push(1);
myStack.Push(15);
myStack.Push(20);
myStack.Push(0);
myStack.Push(-10);
myStack.Push(50);
Console.WriteLine(myStack.GetMinValue());
myStack.Pop();
Console.WriteLine(myStack.GetMinValue());
myStack.Pop();
Console.WriteLine(myStack.GetMinValue());
Console.ReadLine();
}
}
public class MyStack
{
public Stack<int> stackData;
public Stack<int> stackMin;
public MyStack()
{
stackData = new Stack<int>();
stackMin = new Stack<int>();
}
public void Push(int number)
{
if (number.GetType() != typeof(int)) throw new ArgumentException("必须输入数字");
if (stackData.Count() == 0)
{
stackData.Push(number);
stackMin.Push(number);
return;
}
stackData.Push(number);
if (stackMin.Peek() > number)
{
stackMin.Push(number);
}
}
public int Pop()
{
if (stackData.Count() == 0) throw new IndexOutOfRangeException("栈对象为空");
var value = stackData.Pop();
if (value == stackMin.Peek())
{
stackMin.Pop();
}
return value;
}
public int GetMinValue()
{
if (stackMin.Count() == 0) throw new IndexOutOfRangeException("最小值栈对象为空");
return stackMin.Peek();
}
}
}