思路:
建立一个辅助栈,每次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;
}