这题是之前无聊的时候写的,先贴出来吧。在此之前还是得感谢CSDN上无私的大神们,关于微软100题,最全面的资料莫过于JULY大神的博客,有兴趣的读者可以见
http://blog.csdn.net/v_july_v/article/details/6870251
设计包含min函数的栈
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
要求函数min、push以及pop的时间复杂度都是O(1)
这一题其实很简单,其关键处在于min函数的时间复杂度要求,其实只要在数据元素中增加一个当前最小值的变量,每次push的时候都更新一下最小值即可。
见代码:
#include <iostream>
using namespace std;
struct MinStackElement
{
int data;
int min;
};
struct MinStack
{
MinStackElement *data;
int size;
int top;
};
MinStack MinStackInit(int maxSize)
{
MinStack stack;
stack.size = maxSize;
stack.data = (MinStackElement *)malloc(sizeof(MinStackElement)*maxSize);
stack.top = 0;
return stack;
}
void MinStackFree(MinStack stack)
{
free(stack.data);
}
void MinStackPush(MinStack &stack,int d)
{
if(stack.top == stack.size)
cout<<"out of stack space.";
MinStackElement* p = &stack.data[stack.top];
p->data = d;
p->min = (stack.top==0?d:stack.data[stack.top-1].min);
if(p->min>d)
p->min = d;
cout<<"stackpush "<<stack.top<<endl;
stack.top++;
//cout<<stack.top<<endl;
//cout<<stack.data[stack.top-1].min<<endl;
}
int MinStackPop(MinStack stack)
{
if(stack.top == 0)
cout<<"stack is empty!";
return stack.data[--stack.top].data;
}
int MinStackMin(MinStack stack)
{
if(stack.top == 0)
cout<<"stack is empty!";
return stack.data[stack.top-1].min;
}
void main()
{
MinStack minStack;
minStack = MinStackInit(30);
for (int i=9 ; i>=1 ; --i)
{
MinStackPush(minStack,i);
//minStack.top++;
cout<<MinStackMin(minStack)<<endl;
}
for (int i=20 ; i>=10 ; --i)
{
MinStackPush(minStack,i);
//minStack.top++;
cout<<MinStackMin(minStack)<<endl;
}
MinStackFree(minStack);
system("pause");
}