C# 栈=>随时读取栈中最小值
1 //原理:利用两个栈,一个记录最小值,一个记录数据。 2 3 4 5 using System; 6 using System.Collections.Generic; 7 using System.Linq; 8 using System.Threading.Tasks; 9 10 namespace StackGetMinValues 11 { 12 public class Program 13 { 14 public void Main(string[] args) 15 { 16 MyStack myStack = new MyStack(); 17 myStack.Push(1); 18 myStack.Push(15); 19 myStack.Push(20); 20 myStack.Push(0); 21 myStack.Push(-10); 22 myStack.Push(50); 23 Console.WriteLine(myStack.GetMinValue()); 24 25 26 myStack.Pop(); 27 Console.WriteLine(myStack.GetMinValue()); 28 29 myStack.Pop(); 30 Console.WriteLine(myStack.GetMinValue()); 31 32 Console.ReadLine(); 33 34 } 35 36 } 37 public class MyStack 38 { 39 public Stack<int> stackData; 40 public Stack<int> stackMin; 41 public MyStack() 42 { 43 stackData = new Stack<int>(); 44 stackMin = new Stack<int>(); 45 } 46 public void Push(int number) 47 { 48 if (number.GetType() != typeof(int)) throw new ArgumentException("必须输入数字"); 49 50 51 if (stackData.Count() == 0) 52 { 53 stackData.Push(number); 54 stackMin.Push(number); 55 return; 56 } 57 58 stackData.Push(number); 59 if (stackMin.Peek() > number) 60 { 61 stackMin.Push(number); 62 } 63 } 64 public int Pop() 65 { 66 if (stackData.Count() == 0) throw new IndexOutOfRangeException("栈对象为空"); 67 var value = stackData.Pop(); 68 if (value == stackMin.Peek()) 69 { 70 stackMin.Pop(); 71 } 72 return value; 73 } 74 public int GetMinValue() 75 { 76 if (stackMin.Count() == 0) throw new IndexOutOfRangeException("最小值栈对象为空"); 77 78 return stackMin.Peek(); 79 } 80 } 81 }