栈的性质:
比如函数调用的时候,程序里会记录函数发生调用的点的状态,为了调用结束后恢复状态;这时候就会用到栈;
先进后出。
#include <iostream>
#include <memory>
#include "stdio.h"
#include "malloc.h"
typedef int ElementType;
struct StackRecord{
int Capacity;
int Top;
int* Array;
};
typedef StackRecord* Stack;
#define minElements 1
Stack CreateStack(int maxElements){
Stack s = NULL;
if (minElements > maxElements){
printf("stack is too small\n");
return s;
}
s = (Stack)malloc(sizeof(Stack));
if (NULL == s){
printf("s create failed\n");
return s;
}
s->Capacity = maxElements;
s->Top = -1;
s->Array = (int*)malloc(s->Capacity * sizeof(int));
if (s->Array == NULL){
printf("s->Array create failed\n");
free(s);
s = NULL;
return s;
}
return s;
}
bool IsEmpty(Stack s){
return (s == NULL || s->Top == -1);
}
bool IsFull(Stack s){
return s->Top == s->Capacity;
}
void Push(int val, Stack s){
if (s == NULL){
return;
}
if (IsFull(s)){
printf("s is full with item:%d\n", val);
return;
}
s->Array[++s->Top] = val;
}
void Pop(Stack s){
if (s == NULL){
return;
}
if (IsEmpty(s)){
printf("s is empty\n");
return;
}
--s->Top;
}
int Top(Stack s){
if (s == NULL){
return -1;
}
if (IsEmpty(s)){
printf("s is empty\n");
return -1;
}
return s->Array[s->Top];
}
void Destory(Stack s){
if (NULL == s){
return;
}
if (s->Array){
free(s->Array);
s->Array = NULL;
}
free(s);
s = NULL;
}
int main(){
Stack s = CreateStack(10);
Push(1, s);
Push(2, s);
printf("%d ", Top(s));
Pop(s);
printf("%d ", Top(s));
Destory(s);
}