包含min函数的最小栈

题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min,push,及pop的时间复杂度都是O(1)。

剑指offer上面的题目。废话不多说,直接上代码:

#include "stdafx.h"
#include <assert.h>
#include <iostream>
#include <stack>
using namespace std;
template <class T>
class StackWithMin
{
public:
	void push(const T& value);
	void pop();
	const T& top()const;
	const T& min()const;
private:
	stack<T> m_data;//数据栈
	stack<T> m_min;//最小栈(辅助栈)
};
template <class T>
void StackWithMin<T>::push(const T& value)
{
	m_data.push(value);
	if (m_min.empty() || value < m_min.top())
	{
		m_min.push(value);
	}
	else
	{
		m_min.push(m_min.top());
	}
}
template <class T>
void StackWithMin<T>::pop()
{
	assert(!m_data.empty()&&!m_min.empty());
	m_data.pop();
	m_min.pop();
}
template <class T>
const T& StackWithMin<T>::min()const
{
	assert(!m_min.empty());
	return m_min.top();
}
template <class T>
const T& StackWithMin<T>::top()const
{
	assert(!m_data.empty());
	return m_data.top();
}
int _tmain(int argc, _TCHAR* argv[])
{
	StackWithMin<int> smin;
	smin.push(3);
	smin.push(4);
	smin.push(2);
	smin.push(1);
	cout << smin.top() << endl;
	cout << smin.min() << endl;
	smin.pop();
	cout << smin.top() << endl;
	cout << smin.min() << endl;
	smin.pop();
	cout << smin.top() << endl;
	cout << smin.min() << endl;
	smin.pop();
	system("pause");
	return 0;
}

leetcode上面也有一道类似的题目。

题目地址:https://leetcode.com/problems/min-stack/

我的solution:

class MinStack {
public:
      MinStack()
     {
         top_index=-1;
         min=INT_MAX;
     }
    void push(int x) {
        if(top_index<0)
        {
            min=INT_MAX;
        }
        top_index++;
        stack[top_index]=x;
        if(x<min) 
        {
            mindata[top_index]=x;
            min=x;
        }
        else 
        {
           mindata[top_index]=min;
        }
        
    }

    void pop() {
        top_index--;
        min=mindata[top_index];
    }

    int top() {
        return stack[top_index];
    }

    int getMin() {
        return mindata[top_index];
    }
private:
    int stack[100000];
    int mindata[100000];
    int top_index;
    int min;
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值