这道题主要考察对代码的分析。
具体分析参考剑指offer30.
时间和内存消耗以及源代码如下:
typedef struct {
int* pbottom;
int count;
} MinStack;
/** initialize your data structure here. */
MinStack* m_data;
MinStack* m_min;
MinStack* minStackCreate() {
m_data = (MinStack*)malloc(sizeof(MinStack));
m_min = (MinStack*)malloc(sizeof(MinStack));
m_data->pbottom = (int*)malloc(20000*sizeof(int));
m_min->pbottom = (int*)malloc(20000*sizeof(int));
m_min->count = 0;
m_data->count = 0;
return m_data;
}
void minStackPush(MinStack* m_data, int x) {
if (m_data->count == 0)
{
m_min->pbottom[(m_min->count)] = x;
}
else
{
if (m_min->pbottom[(m_min->count)-1] > x)
{
m_min->pbottom[(m_min->count)] = x;
}
else
{
m_min->pbottom[(m_min->count)]=
m_min->pbottom[(m_min->count)-1];
}
}
(m_min->count)++;
m_data->pbottom[(m_data->count)] = x;
(m_data->count)++;
}
void minStackPop(MinStack* m_data) {
if (m_data->count > 0)
{
m_data->pbottom[(m_data->count)--] = NULL;
m_min->pbottom[(m_min->count)--] = NULL;
}
}
int minStackTop(MinStack* m_data) {
if (m_data->count > 0)
{
return m_data->pbottom[(m_data->count)-1];
}
return NULL;
}
int minStackMin(MinStack* m_data) {
if (m_min->count > 0)
{
return m_min->pbottom[(m_min->count)-1];
}
return NULL;
}
void minStackFree(MinStack* m_data) {
if (m_data->count > 0)
{
free(m_data->pbottom);
free(m_data);
free(m_min->pbottom);
free(m_min);
}
}
/**
* Your MinStack struct will be instantiated and called as such:
* MinStack* obj = minStackCreate();
* minStackPush(obj, x);
* minStackPop(obj);
* int param_3 = minStackTop(obj);
* int param_4 = minStackMin(obj);
* minStackFree(obj);
*/