顺序栈
#include <stdio.h>
#include <stdlib.h>
#define STACK_MAX 100
typedef int DT;
typedef struct{
int size;
int top;
DT data[STACK_MAX];
} stack;
void init(stack *st) /*初始化顺序栈*/
{
st->size=0;
st->top=-1;
}
DT pop(stack *a) /*出栈*/
{
if (a->size==0) {
fprintf(stderr,"STACK IS EMPTY");
exit(-1);
}
a->size--;
return a->data[a->top--];
}
void push(stack *a,DT tdata) /*入栈*/
{
if (a->size==STACK_MAX) {
fprintf(stderr,"STACK IS FULL");
exit(1);
}
a->size++;
a->data[++(a->top)]=tdata;
}
int main(void) /*试验*/
{
stack st;
init(&st);
push(&st,5);
push(&st,6);
printf("%d",pop(&st));
return 0;
}
//---------------------------------------------------------------------------
链栈:
//---------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
typedef int DT;
typedef struct node{
DT data;
struct node *next;
} node;
typedef struct{
unsigned int cnt;
node *top;
} stack;
stack *create(void) /*创建空栈*/
{
stack *rt=(stack*)malloc(sizeof(stack));
rt->cnt=0;
rt->top=NULL;
return rt;
}
DT pop(stack *s) /*出栈*/
{
node *dl=s->top;
DT rt;
if (dl==NULL) {
fprintf(stderr,"ERROR! STACK IS EMPTY/n");
exit(-1);
}
s->top=dl->next;
s->cnt--;
rt=dl->data;
free(dl);
return rt;
}
void push(stack *s,DT tdata) /*入栈*/
{
node *td=(node *)malloc(sizeof(node));
td->data=tdata;
td->next=s->top;
s->top=td;
s->cnt++;
}
int main(void) /*试验*/
{
stack *st=create();
push(st,5);
push(st,6);
printf("%d",pop(st));
return 0;
}