#include<stdio.h>
#include<stdlib.h>
typedef struct{
double* values;
int top;
int maxTop;
} Stack;
bool CreateStack(Stack* stack, int size) {
if (size <= 0)
return false;
stack->values = (double*)malloc(sizeof(double) * size);
stack->top = -1;
stack->maxTop = size - 1;//max的最大index是size-1
return true;
}
bool IsEmpty(Stack* stack) {
if (stack->top == -1)
return true;
else
return false;
}
bool IsFull(Stack* stack) {
if (stack->top == stack->maxTop)
return true;
else
return false;
}
bool Top(Stack* stack, double* x) {
if (stack->top == -1) {
return false;
}
else {
*x = stack->values[stack->top];
return true;
}
}
bool Push(Stack* stack, double x) {
if (IsFull(stack))
return false;
stack->values[++stack->top] = x;
return true;
}
bool Pop(Stack* stack, double* x) {
if (stack->top == -1)
return false;
else {
*x = stack->values[stack->top];//
stack->top--;
return true;
}
}
/*void DisplayStack(Stack* stack) {
int i;
for (i = stack->top; i > 0; i--) {
printf("%d\n", stack->values[i]);
}*/
void DestroyStack(Stack** pstack) {
free((*pstack) ->values);
free(*pstack);
*pstack= NULL;
//frees the memory occupied by the stack values and stack struct
// 将stack values和stack struct占用的内存free掉
//point the stack to NULL
//将stack指向NULL
}
#include "stack.h"
#include<stdio.h>
#include<stdlib.h>
void DisplayStack(Stack* stack)
{
if (IsEmpty(stack) == false)
{
int cur = stack->top;
while (cur >= 0)
{
printf("%f\n", stack->values[cur -- ]);
}
}
}
int main() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
double val;
CreateStack(stack, 5);
Push(stack, 5);
Push(stack, 6.5);
Push(stack, -3);
Push(stack, -8);
DisplayStack(stack);
printf("-------------------\n");
if(Top(stack, &val))
printf("Top: %.2f\n", val);
Pop(stack, &val);
if(Top(stack, &val))
printf("Top: %.2f\n", val);
printf("-------------------\n");
while(!IsEmpty(stack))
Pop(stack, &val);
DisplayStack(stack);
printf("-------------------\n");
Push(stack,5);
DisplayStack(stack);
printf("-------------------\n");
DestroyStack(&stack);
DisplayStack(stack);
printf("-------------------\n");
}
```c
```