栈(Stack)
以下为栈的定义、初始化、进栈、出栈、取栈顶操作
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAXSIZE 100
typedef struct{
int *base;
int *top;
int size;
}SeqStack;
void initialize_stack(SeqStack *S)//栈的初始化
{
S->base=(int*)malloc(MAXSIZE*sizeof(int));
if(!S->base) exit(1); //分配空间失败
S->top=S->base;
S->size=MAXSIZE;
}
int judge_empty(SeqStack S)//判断是否为空栈
{
if(S.base==S.top) return 0;
else return 1;
}
void in_stack(SeqStack *S,int x)//入栈
{
if(S->top-S->base==S->size) printf("栈满!");
else *(S->top++)=x;
}
void out_stack(SeqStack *S,int x)//出栈
{
if(S->base==S->top) printf("栈空!");
else x=*(--S->top);
}
void get_top(SeqStack S)//取栈顶元素
{
if(S.base==S.top) printf("栈空!");
else printf("栈顶元素为:%d",*(S.top-1));
}
main()
{
SeqStack S;
initialize_stack(&S);
if(!judge_empty(S)) printf("栈空!\n");
for(int i=1;i<10;i++)
{
in_stack(&S,i*3);
}
int a;
out_stack(&S,a);
get_top(S);
return 0;
}
运行结果为: