2022.2.10
栈及其基本操作
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<stdbool.h>
#define Max_op 50
#define ElemType int
typedef struct Stack
{
ElemType *data;
int top,size;
}Stack;
//初始化
Stack * Init(int n){
Stack *p=(Stack *)malloc(sizeof(Stack));
p->data=(ElemType *)malloc(sizeof(ElemType)*n);
p->size=n;
p->top=-1;
return p;
}
//判空*
bool Empty(Stack *p){
if(p==NULL)return false;
return p->top==-1;
}
//返回栈顶元素
ElemType FindTopElem(Stack *p){
if(p==NULL)return false;
if(Empty(p))return false;
return p->data[p->top];
}
//入栈
bool push(Stack *p,int val){
if(p==NULL)return false;
if(p->top+1==p->size)return false;
p->top+=1;
p->data[p->top]=val;
return true;
}
//出栈
bool pop(Stack *p){
if(p==NULL)return false;
if(p->top==-1)return false;
p->top--;
return false;
}
//销毁栈
bool Clear(Stack *p){
if(p==NULL)return false;
free(p->data);
free(p);
return true;
}
//输出栈
bool Output(Stack *p){
if(p==NULL)return false;
printf("Stack has %d elem\n[",p->top+1);
for(int i=p->top;i>=0;i--){
printf("%d-",p->data[i]);
}
printf("]\n");
}
//测试函数
int main(){
srand(time(NULL));
Stack *s=Init(Max_op);
for(int i=0;i<Max_op;i++){
int op=rand()%2,val=rand()%100;
switch (op){
case 0:{
int a=push(s,val);
printf("%d push to Stack==%d\n",val,a);
}break;
case 1:{
printf("pop %d from Stack\n",s->data[s->top]);
pop(s);
}
default:
break;
}
Output(s);
}
}