/*顺序栈的基本操作(C语言实现版)*/
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 5 /*指定栈的初始空间大小*/
#define STACK_INC 1 /*指定自增大小*/
/*定义栈*/
typedef struct {
int *top ; /*栈顶指针,指向int型成员*/
int *base ; /*栈底指针,指向int型成员*/
int StackSize ; /*栈的成员数量*/
} Stack;
/*1、初始化栈*/
int Init(Stack *s) {
s->base = (int *)malloc(STACK_SIZE*sizeof(int)) ;
if(!s->base)
{
printf("malloc Error! \n") ;
return -1 ;
}
s->top = s->base ; /*注意空栈标志*/
s->StackSize = STACK_SIZE ;
return 0 ;
}
/*2、入栈*/
int Push(Stack *s ,int e){
if(s->top - s->base == s->StackSize) /*如果栈满了,重新追加空间*/
{
s->base =(int *)realloc(s->base ,(STACK_INC+s->StackSize)*sizeof(int)) ;
if(!s->base){
printf("realloc Error! \n") ;
return -1 ;
}
s->top =s->base+ s->StackSize ;
s->StackSize += STACK_INC ;
}
*(s->top) = e ;
s->top++ ;
return 0 ;
}
/*3、出栈,存在e里面*/
int Pop(Stack *s , int *e){
/*先判断是否为空栈*/
if(s->base == s->top)
return -1 ;
s->top-- ;
*e = *(s->top) ;
return 0 ;
}
/*4、获取栈的长度*/
int GetLen(Stack *s){
return (s->top - s->base);
}
/*5、遍历打印栈*/
void PrintStack(Stack *s){
int *tmp ;
tmp = s->top ;
printf("PrintStack :\n");
while(tmp != s->base){
printf("%d \n" , *--tmp);
}
printf("The End ! \n");
}
int main(void){
Stack s ;
int e ;
int ret ;
ret = Init(&s) ;
Push(&s,1) ;
Push(&s,2) ;
Push(&s,3) ;
Push(&s,4) ;
Push(&s,5) ;
Push(&s,6) ;
Push(&s,7) ;
Push(&s,8) ;
PrintStack(&s) ;
printf("GetLen1 = %d \n" ,GetLen(&s)) ;
Pop(&s ,&e) ;
printf("Pop = %d\n" , e) ;
printf("GetLen2 = %d \n" ,GetLen(&s)) ;
PrintStack(&s) ;
return ret;
}
顺序栈基本操作
最新推荐文章于 2022-07-21 22:15:26 发布