剑指offer 面试题21 包含min函数的栈

思路:

    建立一个辅助栈,每次push的时候同时push当前的最小值到辅助栈。


#include <stdio.h>
#include <stdlib.h>

#define STACKSIZE 1024

typedef struct Stack{
	int data[STACKSIZE];
	int vice[STACKSIZE];
	int topIndex;
}MinStack;

MinStack* init(MinStack *s);
int min(MinStack *s);
int top(MinStack *s);
int pop(MinStack *s);
MinStack* push(MinStack *s, int data);

int main(int argc, char *argv[])
{
	int arr[] = {3,1,5,4,2,8,0,7,9};
	MinStack *s = NULL;
	int i, t, m;
	for(i = 0 ; i<sizeof(arr)/sizeof(int) ; i++){
		s = push(s, arr[i]);
	}
	
	for(i = 0 ; i<sizeof(arr)/sizeof(int) ; i++){
		m = min(s);
		t = pop(s);
		printf("m = %d\t t = %d\n", m, t);
	}           
	printf("\n");
	

	return 0;
}

int min(MinStack *s){
	if((s == NULL)||(s->topIndex == -1)){
		printf("MinStack is NULL");
		return 0;
	}
	return s->vice[s->topIndex];
}
MinStack* init(MinStack *s){
	if(s == NULL){
		s = (MinStack*)(malloc(sizeof(MinStack)));
	}
	
	s->topIndex = -1;
	return s;
}
int top(MinStack *s){
	if((s == NULL)||(s->topIndex == -1)){
		printf("MinStack is NULL");
		return 0;	
	}
	return s->data[s->topIndex];
}
int pop(MinStack *s){
	if((s == NULL)||(s->topIndex == -1)){
		printf("MinStack is NULL");
		return 0;	
	}
	int d = s->data[s->topIndex];
	s->topIndex--;
//	s->topIndex = s->topIndex-1; 
	return d;
}
MinStack* push(MinStack *s, int data){
	if(s == NULL){
		s = init(s);                                                              	                                                
	}
	
	if(s->topIndex >= STACKSIZE){     //检查 
	  printf("out of range!\n");
	  return s;
	}
	s->topIndex = s->topIndex+1;
	s->data[s->topIndex] = data;
	if(s->topIndex == 0){            //注意首个元素插入时候的特殊情况 
		s->vice[s->topIndex] = data;
		return s;	
	}
	
	if(data < s->vice[s->topIndex-1]){
		s->vice[s->topIndex] = data;
	}
	else{
		s->vice[s->topIndex] = s->vice[s->topIndex-1] ;
	}

	return s;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值