在棧中增加min函數

定義棧的數據結構,要求添加一個min函數,能夠得到棧的最小元素。
要求函數min、push以及pop的時間複雜度都是O(1)。

算法:在棧中設置一個輔助棧來保存最小值

代碼:

/** 
爲棧增加一個min函數,獲取棧中的最小值,複雜度爲1
** author :xiaozhi xiong 
** date:2014-02-08
**/ 
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
int MAX_STACK=50;
struct stack
{
	int a[50];
	int min[50 ];
	int top;
	int top_min;
};
//初始化棧
void InitStack(struct stack *p)
{
 
   p->top=-1;
   p->top_min=-1;
}
//入棧
void PushStack(struct stack* p,int value)
{
	if(p->top>MAX_STACK)
	{
		printf("棧滿\n");
		return;
	}
	else
	{
		if(p->top_min==-1)
		{
			p->a[++p->top]=value;
			p->min[++p->top_min]=value;
		}
		else
		{
			p->a[++p->top]=value;
			if(p->min[p->top_min]>=value)
				p->min[++p->top_min]=value;
		}
	}
}
int PopStack(struct stack *p)
{
	int value;
	if(p->top==-1)
	{
		printf("空棧\n");
		return -999;
	}
	else
	{
		value=p->a[p->top];
		p->a[p->top--];
		if(value==p->min[p->top_min])
		{
			p->top_min--;
		}
		return value;
	}
}
int GetMinInStack(struct stack *p)
{
	if(p->top_min==-1)
	{
		printf("空棧\n");
		return -9999;
	}
	else 
	{
		return p->min[p->top_min];
	}
}
int main(void)
{
	struct stack *stack_min;
	int popValue;
	int minInStack;
	stack_min=(struct stack *)malloc(sizeof(struct stack *));
	InitStack(stack_min);
	PushStack(stack_min,10);
    PushStack(stack_min,1);
	PushStack(stack_min,101);
	PushStack(stack_min,-1);
	PushStack(stack_min,-2);
	PushStack(stack_min,-3);

	popValue=PopStack(stack_min);
	minInStack=GetMinInStack(stack_min);
	printf("出棧%d  棧中最小值%d\n",popValue,minInStack);

	popValue=PopStack(stack_min);
	minInStack=GetMinInStack(stack_min);
	printf("出棧%d  棧中最小值%d\n",popValue,minInStack);
	
	popValue=PopStack(stack_min);
	minInStack=GetMinInStack(stack_min);
	printf("出棧%d  棧中最小值%d\n",popValue,minInStack);
	getchar();
    return 0;
}

發佈了38 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章