C++ 设计最小值栈

最小值栈,即栈顶元素是当前栈内元素的最小值

分析:

 代码如下:

class MyMinStack
{
public:
	void push(int x)
	{
		data.push(x);
		if (MinStack.empty())
		{
			MinStack.push(x);
		}
		else
		{
			if (x > MinStack.top())
			{
				x = MinStack.top();
			}
			MinStack.push(x);
		}
	}
	void pop()
	{
		data.pop();
		MinStack.pop();
	}
	int GetTop()
	{
		return data.top();
	}
	int GetMin()
	{
		return MinStack.top();
	}
private:
	stack data;
	stackMinStack;
};
void main()
{
	MyMinStack ms;
	ms.push(1);
	ms.push(3);
	ms.push(4);
	cout << "min= " << ms.GetMin() << endl;
	cout << "top= " << ms.GetTop() << endl;
}

运行结果:

 

你可能感兴趣的:(C++笔记,c++,算法)