栈(Stack)
简介
特点:先进后出
入栈: 将元素放入这一行为称为入栈
出栈: 将栈顶元素取出这一行为称为出栈
栈顶: 最顶端的元素
栈只有一个出入口,所有元素的进出只能在该出入口进行,且同一时间只能由一个元素进或出
代码参考
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef int DataType;
typedef struct{
DataType num[MAX];
int top;
}SeqStack;
//初始化
void Init(SeqStack *s){
s->top = 0;
}
//获取状态
int GetStatus(const SeqStack *s){
if(s->top == MAX) return 1;
else if(s->top == 0) return -1;
return 0;
}
//入栈
void Insert(SeqStack *s,DataType val){
if(s->top == MAX){
printf("The stack is fulled.\n");
return;
}
s->top += 1;
s->num[s->top - 1] = val;
}
//出栈
void Delete(SeqStack *s){
if(s->top == 0){
printf("The stack is empty!\n");
return ;
}
s->top -= 1;
}
//打印
void Print(const SeqStack* s){
unsigned char i = 0;
unsigned char count = 0;
for(i = 0;i < s->top;i++){
printf("%d ",s->num[i]);
if(++count == 5){
count = 0;
printf("\n");
}
}
}
int main(){
SeqStack *s;
s = (SeqStack*)malloc(sizeof(SeqStack));
Init(s);
printf("Insert:");
int i;
for(i = 0;i < 5;++i){
Insert(s,i);
}
Print(s);
printf("Delete1:");
Delete(s);
Print(s);
printf("\n");
printf("Delete2:");
Delete(s);
Print(s);
return 0;
}