- 实现一个栈,要求实现: Push(入栈)、Pop(出栈)、Min(返回最小值)的时间复杂度为O(1)
思路: 1.用两个数组实现 2.不在每次都入最小栈
1.P1.h
#pragma once
#include <stdlib.h>
#include <stdio.h>
/*
实现一个栈,要求实现:
Push(入栈)、Pop(出栈)、Min(返回最小值)的时间复杂度为O(1)
1.用两个数组实现
2.不在每次都入最小栈
*/
typedef int DataType;
#define MAX_TOP (100)
// 最小栈结构定义
typedef struct MinStack {
DataType array1[MAX_TOP]; // 普通数据 (黑色)
int top1;
DataType array2[MAX_TOP]; // 最小数据(红色)
int top2;
} MinStack;
// 初始化
void Init(MinStack *pS)
{
pS->top1 = pS->top2 = 0;
}
// 入栈
void Push(MinStack *pS, DataType data)
{
// 1.将数据存入数组1
pS->array1[pS->top1++] = data;
// 2.若数组2为空(即栈顶=0)或者将要存入的 data <= 数组2[top2 - 1],
// 则将此data也存入数组2
if (pS->top2 == 0 || data < pS->array2[pS->top2 - 1]) {
pS->array2[pS->top2++] = data;
}
}
// 出栈
void Pop(MinStack *pS)
{
if (pS->array1[pS->top1 -1] == pS->array2[pS->top2 - 1]) {
pS->top2--;
}
pS->top1--;
}
// 返回栈数据个数
DataType MinStackSize(MinStack *pS)
{
return pS->array1[pS->top1 - 1];
}
// 返回最小值
DataType Min(MinStack *pS)
{
return pS->array2[pS->top2 - 1];
}
void TestMinStack()
{
MinStack minStack;
Init(&minStack);
Push(&minStack, 9);
Push(&minStack, 5);
Push(&minStack, 2);
Push(&minStack, 7);
Push(&minStack, 1);
printf("%d\n", Min(&minStack));
Pop(&minStack);
printf("%d\n", Min(&minStack));
system("pause");
}
2.Main.c
#include "P1.h"
int main()
{
TestMinStack();
return 0;
}