定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

// test14.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<exception>
#include <initializer_list>
#include<stack>
using namespace std;

class Solution {
public:
	void push(int value) {
			stack1.push(value);
	}
	void pop() {
		stack1.pop();
	}
	int top() {
		return stack1.top();
	}

	int min() { //用一另一个栈存放读入的数据
		int minNum=0;
		if(!stack1.empty())
		{ 
			minNum =stack1.top();
			stack2.push(stack1.top());
			stack1.pop();
		}
		while (!stack1.empty())
		{
			if (minNum > stack1.top())
			{
				minNum = stack1.top();
				stack2.push(stack1.top());
				stack1.pop();
			}
			else
			{
				stack2.push(stack1.top());
				stack1.pop();
			}
		}
		while(!stack2.empty())
		{
			stack1.push(stack2.top());
			stack2.pop();
		}
		return minNum;
	}
private:
	stack<int> stack1;
	stack<int> stack2;
};

int main()
{
	
	Solution so;
	so.push(2);
	so.push(1);
	so.push(3);
	so.push(4);
	so.push(4);
	so.push(5);
	so.push(3);
	
	cout <<"栈顶元素:" <<so.top()<<endl;
	cout << "最小元素:"<< so.min() << endl;
	cout << endl;

	so.pop();
	cout << "栈顶元素:" << so.top() << endl;
	cout << "最小元素:" << so.min() << endl;
	cout << endl;

	so.pop();
	cout << "栈顶元素:" << so.top() << endl;
	cout << "最小元素:" << so.min() << endl;
	cout << endl;

	cout << endl;
	return 0;
}
posted @ 2016-10-10 13:48  wdan2016  阅读(2563)  评论(0编辑  收藏  举报