定義棧的數據結構,請在該類型中實現一個能夠得到棧最小元素的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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM