定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。
要求函数min、push以及pop的时间复杂度都是O(1)。
结合链表一起做。
首先我做插入以下数字:10,7,3,3,8,5,2, 6
0: 10 -> NULL (MIN=10, POS=0)
1: 7 -> [0] (MIN=7, POS=1) 用数组表示堆栈,第0个元素表示栈底
2: 3 -> [1] (MIN=3, POS=2)
3: 3 -> [2] (MIN=3, POS=3)
4: 8 -> NULL (MIN=3, POS=3) 技巧在这里,因为8比当前的MIN大,所以弹出8不会对当前的MIN产生影响
5:5 -> NULL (MIN=3, POS=3)
6: 2 -> [2] (MIN=2, POS=6) 如果2出栈了,那么3就是MIN
7: 6 -> [6]
代码如下:
#include<iostream>
#include<stdlib.h>
#include<malloc.h>
using namespace std;
#define STACK_MAX_SIZE 10
#define STACK_ADD_SIZE 10
struct MyStack
{
int min;
int data;
}*myStack;
struct MinStack
{
MyStack *data;
int top;
int base;
int size;
}*minStack;
MinStack* MinStack_Create()
{
MinStack *_stack;
_stack = (MinStack*)malloc(sizeof(MinStack));
return _stack;
}
bool MinStack_Init(MinStack *_stack)
{
_stack->size = 0;
_stack->base = 0;
_stack->top = _stack->base;
_stack->data = (MyStack*)malloc(sizeof(MyStack) * STACK_MAX_SIZE);
if(_stack->data != NULL)
return false;
else
return true;
}
bool MinStack_Empty(MinStack *_stack)
{
return (_stack->top == _stack->base);
}
bool MinStack_Push(MinStack *_stack,int value)
{
if(_stack->top == _stack->size)
{
_stack->data = (MyStack*)realloc(_stack->data,(_stack->size + STACK_ADD_SIZE) * sizeof(MyStack));
if(_stack->data == NULL)
return false;
}
_stack->data[_stack->top].data = value;
if(MinStack_Empty(_stack))
_stack->data[_stack->top++].min = value;
else if(value < _stack->data[_stack->top - 1].min)
_stack->data[_stack->top++].min = value;
else
_stack->data[_stack->top++].min = _stack->data[_stack->top - 1].min;
return true;
}
bool MinStack_Pop(MinStack *_stack,int &value)
{
if(MinStack_Empty(_stack))
return false;
value = _stack->data[--_stack->top].data;
return true;
}
bool MinStack_Min(MinStack *_stack,int &min)
{
if(MinStack_Empty(_stack))
return false;
min = _stack->data[_stack->top - 1].min;
return true;
}
int main()
{
MinStack *_stack = MinStack_Create();
int i;
int value;
bool flag = true;
while(flag)
{
cout<<"1.STACK INIT 2.STACK EMPTY 3.STACK PUSH 4.STACK POP 5.STACK MIN 6.QUIT"<<endl;
cin>>i;
switch(i)
{
case 1:
MinStack_Init(_stack);
break;
case 2:
if(MinStack_Empty(_stack))
cout<<"The Stack is Empty!!"<<endl;
else
cout<<"The Stack is not Empty!!"<<endl;
break;
case 3:
cout<<"Input the value : ";
cin>>value;
if(MinStack_Push(_stack,value))
cout<<"Push Stack Successful!!"<<endl;
else
cout<<"Push Stack Failure!!"<<endl;
break;
case 4:
if(MinStack_Pop(_stack,value))
cout<<"The value of Pop is "<<value<<endl;
else
cout<<"Pop Stack Failure!!"<<endl;
break;
case 5:
if(MinStack_Min(_stack,value))
cout<<"The min of Stack is "<<value<<endl;
else
cout<<"Min Operation failure!!"<<endl;
break;
default:
flag = false;
break;
}
}
return 0;
}