題目:
定義棧的數(shù)據(jù)結(jié)構(gòu)艇肴,要求添加一個(gè)min函數(shù)激蹲,能夠得到棧的最小元素棉磨。
要求函數(shù)min、push以及pop的時(shí)間復(fù)雜度都是O(1)学辱。
這個(gè)題目首先需要實(shí)現(xiàn)一個(gè)棧結(jié)構(gòu)乘瓤,然后每個(gè)棧頂?shù)脑乩锩娉吮4鎣alue,還需要保存當(dāng)前棧內(nèi)最小值策泣,push元素進(jìn)棧時(shí)需要判斷衙傀,如果push的元素比棧頂保存的最小值還小,新的最小值為push的元素萨咕,否則就沿用上一個(gè)棧頂元素的最小值:
solution
<pre><code>
include "stdio.h"
include "stdlib.h"
//定義棧元素的結(jié)構(gòu)體
typedef struct MinStackElement{
int value;
int mini;
} MinStackElement;
typedef struct MinStack{
MinStackElement* data;
int size;//棧大小
int top;//記錄棧頂?shù)奈恢?br>
} MinStack;
//初始化一個(gè)棧统抬,并返回棧指針
MinStack* initialStack(int maxSize){
//初始化指針,給指針一個(gè)內(nèi)存空間
MinStack p=(MinStack)malloc(sizeof(MinStack));
p->size=maxSize;
p->top=0;
p->data=(MinStackElement)malloc(sizeof(MinStackElement)maxSize);
printf("initial stack success!! \n");
return p;
}
//給stackpush一個(gè)變量危队,top指向棧頂?shù)膇ndex蓄喇,mini記錄當(dāng)前最小值
void stackpush(int value,MinStack *stack){
printf("pushing %d to stack\n",value);
if (stack->top>=stack->size){
printf("sorry,the stack is full\n");
return;
}
MinStackElement item;
item.value=value;
//item.mini
if (stack->top==0){
item.mini=item.value;
}else{
if(item.value<stack->data[stack->top-1].value)
item.mini=item.value;
else
item.mini=stack->data[stack->top-1].mini;
}
stack->data[stack->top]=item;
stack->top++;
}
//讀取當(dāng)前棧的最小值
int min(MinStack *stack){
if (stack->top==0){
printf("the stack is empty!\n");
return -1;
}else{
return stack->data[stack->top-1].mini;
}
}
int main(){
MinStack *stack=initialStack(10);
printf ("the minimal is %d\n",min(stack));
stackpush(10,stack);
printf ("the minimal is %d\n",min(stack));
stackpush(9,stack);
printf ("the minimal is %d\n",min(stack));
stackpush(8,stack);
printf ("the minimal is %d\n",min(stack));
stackpush(7,stack);
printf ("the minimal is %d\n",min(stack));
stackpush(6,stack);
printf ("the minimal is %d\n",min(stack));
stackpush(8,stack);
printf ("the minimal is %d\n",min(stack));
stackpush(1,stack);
printf ("the minimal is %d\n",min(stack));
return 0;
}
</code></pre>