資料結構--順序棧
阿新 • • 發佈:2018-11-03
文章目錄
sequence_ctack.h
#ifndef __SEQUENCE_STACK_H__
#define __SEQUENCE_STACK_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct{
datatype *data;
int maxlen;
int top;
}seqstack;
seqstack *create_seqstack(int len);
void clear_seqstack(seqstack *L);
void free_seqstack(seqstack *L);
int is_empty_seqstack(seqstack *L);
int is_full_seqstack(seqstack *L);
int push_seqstack(seqstack *L,datatype x);
datatype pop_seqstack(seqstack *L);
datatype get_top_seqstack(seqstack * L);
#endif
sequence_stack.c
#include "sequence_stack.h"
seqstack *create_seqstack(int len)
{
seqstack * H;
if((H = (seqstack *)malloc(sizeof(seqstack))) == NULL)
{
printf("malloc no memory!\n");
return NULL;
}
if((H->data = (datatype *)malloc(len * sizeof(datatype))) == NULL )
{
printf("malloc no memory!\n");
return NULL;
}
H->maxlen = len;
H->top = -1;
return H;
}
void clear_seqstack(seqstack *L)
{
L->top = -1;
}
void free_seqstack(seqstack *L)
{
free(L->data);
L->data = NULL;
free(L);
L = NULL;
}
int is_empty_seqstack(seqstack *L)
{
return(L->top == -1 ? 1 : 0);
}
int is_full_seqstack(seqstack *L)
{
return(L->top == (L->maxlen-1) ? 1 : 0);
}
int push_seqstack(seqstack *L,datatype x)
{
if(is_full_seqstack(L))
{
printf("stack is full!\n");
return -1;
}
else
{
L->top++;
L->data[L->top] = x;
return 0;
}
}
datatype pop_seqstack(seqstack *L)
{
if(is_empty_seqstack(L))
{
printf("stack is empty!\n");
return -1;
}
else
{
L->top--;
return L->data[L->top+1];
}
}
datatype get_top_seqstack(seqstack *L)
{
if(is_empty_seqstack(L))
{
printf("stasic is empty!\n");
return -1;
}
else
{
return L->data[L->top];
}
}
main.c
#include "sequence_stack.h"
int main(int argc, const char *argv[])
{
int n = 5;
seqstack *S;
S = create_seqstack(n);
push_seqstack(S,10);
push_seqstack(S,20);
push_seqstack(S,30);
push_seqstack(S,40);
push_seqstack(S,50);
push_seqstack(S,60);
printf("%d\n",get_top_seqstack(S));
while(!is_empty_seqstack(S))
{
printf("%d\t",pop_seqstack(S));
}
puts("");
printf("%d\n",get_top_seqstack(S));
free_seqstack(S);
printf("%d\n",get_top_seqstack(S));
return 0;
}
執行結果