最小栈的实现

前言

要求:

实现一个栈,改栈带有出栈,入栈,和取栈中最小数。要求时间复杂度都是o(1);

实现

C# 代码:

class Program
{
	private static Stack<int> mainStack = new Stack<int>();

	private static Stack<int> MinStack = new Stack<int>();

	private static void pushStack(int element)
	{
		mainStack.Push(element);
		if (MinStack.Count == 0 || element <= MinStack.Peek())
		{
			MinStack.Push(element);
		}
	}

	private static int popStack()
	{
		if (mainStack.Count == 0)
		{
			throw new Exception("没有对象了");
		}
		if (MinStack.Peek() == mainStack.Peek())
		{
			MinStack.Pop();
		}
		return mainStack.Pop();
	}

	private static int getMini()
	{
		if (MinStack.Count == 0)
		{
			throw new Exception("没有对象了");
		}
		return MinStack.Pop();
	}

	static void Main(string[] args)
	{
		popStack();
		Console.WriteLine("Hello World!");
	}
}
posted @ 2020-03-16 10:03  敖毛毛  阅读(110)  评论(0编辑  收藏  举报