题目:
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。 要求函数min、push以及pop的时间复杂度都是O(1)。
设计包含min函数的栈.cpp : Defines the entry point for the console application.
// 设计包含min函数的栈.cpp : Defines the entry point for the console application.
//
/*
题目:
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。 要求函数min、push以及pop的时间复杂度都是O(1)。
*/
#include "stdafx.h"
#include <iostream>
#include "MinStack.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
CMinStack stack;
cout << "进栈,栈中的值为:" << endl;
stack.push(24);
stack.push(21);
stack.push(25);
stack.push(28);
stack.push(10);
stack.push(5);
int minValue = 0;
cout << "栈中最小值为:" << endl;
stack.Min(minValue);
cout << "取出栈中的值:" << endl;
stack.pop(minValue);
stack.pop(minValue);
cout << "取出栈中值之后,最小值为:" << endl;
stack.Min(minValue);
system("pause");
return 0;
}
CMinStack::CMinStack(void)
{
m_n_stackCount = 0; //初始化索引为0
}
CMinStack::~CMinStack(void)
{
}
//判断栈是否为NULL
bool CMinStack::IsEmpty()
{
return (m_n_stackCount <= 0);
}
//进栈,包括Value,MinValue的值
bool CMinStack::push(int data)
{
if(m_n_stackCount > MAX_STACK_SIZE)
{
//此时栈已经满了
return false;
}
StackElemnt ele;
ele.Value = data;
if (IsEmpty())
{
//栈为NULL;
ele.MinVale = data;
}else
{
if (m_StackElement[m_n_stackCount-1].MinVale > data)
{
ele.MinVale = data;
}else
{
ele.MinVale = m_StackElement[m_n_stackCount-1].MinVale;
}
}
m_StackElement[m_n_stackCount] = ele;
cout << "Value:" << m_StackElement[m_n_stackCount].Value << " MinValue:" << m_StackElement[m_n_stackCount].MinVale << endl;
m_n_stackCount++;
return true;
}
bool CMinStack::pop(int &popdate)
{
if (IsEmpty())
{
return false;
}
m_n_stackCount--;
popdate = m_StackElement[m_n_stackCount].Value;
cout << "第" << m_n_stackCount << "栈已被取出" << endl;
return true;
}
bool CMinStack::Min(int minData)
{
if (IsEmpty())
{
return false;
}
minData = m_StackElement[m_n_stackCount-1].MinVale;
cout << minData << endl;
return true;
}
头文件:MinStack.h
#pragma once
#define MAX_STACK_SIZE 100
//定义栈中所存在的元素
typedef struct minStackElement
{
int Value; //进栈的值
int MinVale; //目前栈中的最小值
}StackElemnt;
class CMinStack
{
public:
CMinStack(void);
~CMinStack(void);
bool IsEmpty();//判断栈是否为NULL
bool push(int data); //将元素data进栈
bool pop(int &popdate);//将元素出栈
bool Min(int minData);//获得栈中最小值
private:
StackElemnt m_StackElement[MAX_STACK_SIZE]; //定义一个栈,他所能承载的容量为MAX_STACK_SIZE
int m_n_stackCount; //进栈索引
};
执行结果: