1、头文件sqstack.h
#include <stdio.h>
#define MAXSIZE 100
typedef struct SqStack
{
void* data[MAXSIZE];
int top; //指向栈顶下标
}SqStack;
void InitStack(SqStack*);
int StackEmpty(SqStack*);
int StackLength(SqStack*);
void ClearStack(SqStack*);
void GetTop(SqStack*, void**);
void PushStack(SqStack*, void*);
void PopStach(SqStack*, void**);
2、相关函数操作文件sqstack.c
#include <stdio.h>
#include <string.h>
#include "SqStack.h"
//栈的初始化
void InitStack(SqStack* S)
{
//空栈
S->top = -1;
memset(S->data, 0, sizeof(S->data));
}
int StackEmpty(SqStack* S)
{
if(S->top == -1)
{
return 1;
}
return 0;
}
void ClearStack(SqStack* S)
{
S->top = -1;
}
void GetTop(SqStack* S, void** e)
{
if(S->top == -1)
{
printf("当前栈为空栈!");
return;
}
*e = S->data[S->top];
}
void PushStack(SqStack* S, void* e)
{
if(S->top == MAXSIZE - 1)
{
printf("栈满,无法压栈!");
return;
}
S->top++;
S->data[S->top] = e;
}
void PopStach(SqStack* S, void** e)
{
if(S->top == -1)
{
printf("空栈,无法出栈!");
return;
}
*e = S->data[S->top];
S->top--;
}
int StackLength(SqStack* S)
{
return S->top+1;
}
3、主函数测试文件main.c
#include <stdio.h>
#include <stdlib.h>
#include "SqStack.h"
typedef struct student
{
int age;
int id;
}stu;
int main()
{
SqStack st;
stu s[10];
InitStack(&st);
int i = 0;
for(i = 0; i < 10; i++)
{
s[i].age = i + 20;
s[i].id = i;
PushStack(&st, &s[i]);
}
printf("当前栈的大小为:%d\n", StackLength(&st));
stu* sp;
for(i = 0; i < 5; i++)
{
GetTop(&st, (void**)&sp);
printf("当前栈顶元素值为:%d, %d\n", sp->age, sp->id);
PopStach(&st, (void**)&sp);
printf("出栈元素值为:%d, %d\n", sp->age, sp->id);
printf("\n");
}
printf("当前栈的大小为:%d\n", StackLength(&st));
ClearStack(&st);
printf("当前栈的大小为:%d\n", StackLength(&st));
//printf("Hello world!\n");
return 0;
}
网友评论