// seq_stack.h -- header of sequence stack
#ifndef __SEQ_STACK_H__
#define __SEQ_STACK_H__
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 8
typedef int datatype;
typedef struct seq_stack{
datatype data[MAX];
int top;
}sstack_t, * psstack_t;
// stack init
psstack_t init();
// push
void push(psstack_t, datatype);
// pop
void pop(psstack_t, datatype*);
// check if empty
bool isEmpty(psstack_t);
// check if full
bool isFull(psstack_t);
// clear
void clear(psstack_t);
// destroy
void destroy(psstack_t*);
// show
void show(psstack_t);
#endif // !__SEQ_STACK_H__
// seq_stack.c -- implement of sequence stack
#include "seq_stack.h"
// stack init
psstack_t init(){
psstack_t s = (psstack_t)malloc(sizeof(sstack_t));
if(!s)
return NULL;
else{
s->top = -1;
return s;
}
}
// push
void push(psstack_t s, datatype d){
if(!s)
return;
else if(!isFull(s)){
s->data[++s->top] = d;
return;
}
}
// pop
void pop(psstack_t s, datatype* pd){
if(!s)
return;
else if(!isEmpty(s)){
*pd = s->data[s->top--];
return;
}
}
// check if empty
bool isEmpty(psstack_t s){
if(!s)
return false;
else
return (s->top == -1);
}
// check if full
bool isFull(psstack_t s){
if(!s)
return false;
else
return (s->top == MAX-1);
}
// clear
void clear(psstack_t s){
if(!s)
return;
else{
s->top = -1;
return;
}
}
// destroy
void destroy(psstack_t* ps){
if(!ps)
return;
else if(!*ps)
return;
else{
free(*ps);
*ps = NULL;
return;
}
}
// show
void show(psstack_t s){
if(!s)
return;
else if(isEmpty(s))
return;
else{
for(int i = s->top; i != -1; i--)
printf("%-4d", s->data[i]);
putchar(10);
return;
}
}
#include "seq_stack.h"
#include <time.h>
int main(){
psstack_t s = init();
push(s, 1);
push(s, 2);
push(s, 3);
push(s, 4);
push(s, 5);
show(s);
clear(s);
for(int i = 0; i < 10; i++)
push(s, rand()%100);
show(s);
datatype ret;
pop(s, &ret);
printf("pop: %d\n", ret);
show(s);
destroy(&s);
return 0;
}
5 4 3 2 1
92 86 35 93 15 77 86 83
pop: 92
86 35 93 15 77 86 83