(微软100题)2.设计包含min 函数的栈。

#include <iostream>
using namespace std;
/*2.设计包含min 函数的栈。
定义栈的数据结构,要求添加一个min 函数,能够得到栈的最小元素。
要求函数min、push 以及pop 的时间复杂度都是O(1)。
ANSWER:
Stack is a LIFO data structure. When some element is popped from the stack, the status will recover to the original status as before that element was pushed. So we can recover the minimum element, too. 
*/
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;
	stack.top ++;
}
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()
{
}

posted @ 2014-02-14 17:32  byfei  阅读(172)  评论(0编辑  收藏  举报