此程序实现了一个查找出栈中最小元素的时间复杂度为0的栈。
此函数在进栈出栈的时候都进行了判断,
进栈时,若当前的元素小于之前的最小元素,则把当前元素记录进该元素的最小元素中,并输出更改最小元素的信息。
出栈时,若当前的最小元素小于出栈后栈中的最小元素,则输出更改最小元素的信息。
代码如下:
#include <stdio.h>
#include <malloc.h>
#include <random>
#define datatype char
typedef struct { // 这个数据类型存储的不只是压栈元素,还存了当前栈中最小元素值
datatype Elem;
datatype Min;
}ElemType;
typedef struct { // Stack define
ElemType *StElem; // 元素指针,指向申请的内存
int size; // 栈的大小,即要申请的StEleme元素的个数
int top;
}Stack;
void Stack_Init(Stack &St , int StSize) // 初始化栈
{
St.StElem = (ElemType *)malloc(sizeof(ElemType) * StSize); // 申请内存以存放元素
St.top = -1;
St.size = StSize;
}
void Min_Find(Stack St , datatype &E) // 查找栈中最小元素,时间复杂度为O
{
if(St.top == -1) {
perror("The Stack is Null , Error !\n");
}
E = St.StElem[St.top].Min;
}
void Stack_Pop(Stack &St , datatype &E) // 出栈
{
bool flag = false;
if(St.top == -1) {
perror("The Stack is Empty , Pop Error !\n");
}
else {
if(St.StElem[St.top - 1].Min > St.StElem[St.top].Min) {
// 如果当前最小栈中元素出栈了,则在出栈后显示新的最小栈中元素
flag = true;
}
E = St.StElem[St.top].Elem;
St.top--;
printf("Pop Elem '%c' Succeed !\n",E);
if(flag) {
printf("The New Min Elem in the Stack is '%c'\n", St.StElem[St.top].Min);
}
}
}
void Stack_Push(Stack &St , datatype E) // 出栈函数
{
if(St.top == St.size - 1) {
perror("The Stack is Full , Push Error !\n");
}
St.top++;
St.StElem[St.top].Elem = E;
St.StElem[St.top].Min = (St.top == 0 ? E : St.StElem[St.top - 1].Min);
printf("Push New Elem '%c' into Stack Succeed !\n",E);
if(St.StElem[St.top].Min > E) {
St.StElem[St.top].Min = E;
printf("The New Min Elem in the Stack is '%c'\n",E);
}
}
void Stack_Free(Stack &St) // 释放申请的内存
{
free(St.StElem);
St.StElem = NULL;
}
void Stack_Test() // 此程序的测试函数
{
Stack S;
datatype E;
Stack_Init(S, 20);
printf("Pushing into Stack...\n");
for (int i = 0; i < 20; i++) {
Stack_Push(S, (datatype)(rand() % 26 + 65));
}
printf("\nPoping from Stack...\n");
while(S.top >= 0) {
Stack_Pop(S, E);
}
Stack_Free(S);
}
int main()
{
Stack_Test();
return 0;
}