码迷,mamicode.com
首页 > Windows程序 > 详细

C# 栈=>随时读取栈中最小值【1】

时间:2015-12-09 21:34:02      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

代码随笔。。。。

 

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();
}
}
}

C# 栈=>随时读取栈中最小值【1】

标签:

原文地址:http://www.cnblogs.com/shidengyun/p/5034280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!