栈的原理
- 先进后出,不能随机访问,只有讲上面的数据Pop之后,才能访问下面的数据
代码
stack.h
#ifndef __STACK_H
#define __STACK_H
#define MAX_SIZE 1024
typedef struct STACK
{
void* Stack_Sqe[MAX_SIZE];
int size;
}Stack;
Stack* Init_Stack(void);
void Push_Stack(Stack* stack, void* data);
void Pop_Stack(Stack* stack);
void* Top_Stack(Stack* stack);
void Clear_Stack(Stack* stack);
void Free_Stack(Stack* stack);
int Size_Stack(Stack* stack);
#endif
stack.c
#include "../include/stack.h"
#include <stdlib.h>
Stack* Init_Stack(void)
{
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->size =0;
for(int i=0; i<MAX_SIZE; i++)
{
stack->Stack_Sqe[i]=NULL;
}
return stack;
}
void Push_Stack(Stack* stack, void* data)
{
if(stack == NULL) return;
if(data == NULL) return;
stack->Stack_Sqe[stack->size++] = data;
}
void Pop_Stack(Stack* stack)
{
if(stack == NULL) return;
stack->Stack_Sqe[stack->size-1]=NULL;
stack->size--;
}
void* Top_Stack(Stack* stack)
{
if(stack == NULL)return NULL;
return stack->Stack_Sqe[stack->size-1];
}
void Clear_Stack(Stack* stack)
{
if(stack == NULL)return;
for(int i=0; i<stack->size; i++)
{
stack->Stack_Sqe[i]=NULL;
}
}
void Free_Stack(Stack* stack)
{
if(stack == NULL)
return;
free(stack);
}
int Size_Stack(Stack* stack)
{
return stack->size;
}
main.c
#include <stdio.h>
#include "../include/stack.h"
typedef struct PERSION
{
char name [64];
int id;
}Person;
int main(void)
{
Stack* stack = Init_Stack();
Person p1={"julain",1};
Person p2={"kerr",2};
Person p3={"mike",3};
Person p4={"july",4};
Push_Stack(stack,&p1);
printf("Push %s %d\n",p1.name,p1.id);
Push_Stack(stack,&p2);
printf("Push %s %d\n",p2.name,p2.id);
Push_Stack(stack,&p3);
printf("Push %s %d\n",p3.name,p3.id);
Push_Stack(stack,&p4);
printf("Push %s %d\n",p4.name,p4.id);
printf("stack size: %d \n\n",stack->size);
printf("开始Pop\n");
while(stack->size)
{
Person* p =(Person*) Top_Stack(stack);
printf("%s %d\n",p->name,p->id);
Pop_Stack(stack);
}
printf("after pop 4 times size: %d \n\n",stack->size);
Free_Stack(stack);
return 0;
}
- 结果: