栈的结构类型,和基本操作如下:
typedef struct{
_type *base; //栈底,第一个元素
_type *top; //栈顶,最后一个元素
int size; //栈的大小
}*stack,st;
void InitStack(stack *S); //初始化栈
void DestroyStack(stack *S); //销毁栈
void push(stack st,_type e); //插入元素
_type pop(stack st); //弹出栈顶元素
_type getTop(stack st); //获得栈顶元素,并不删除
int length(stack st); //返回栈的元素个数
int isEmpty(stack st); //是否为空,c语言中没有bool类型
全部代码如下:
#include "stdio.h"
#include "stdlib.h"
#define _type int //栈的数据类型,不能加逗号,不然会出错
#define stack_size 100 //栈的大小
#define add_size 10 //不够时的增量
#define endFlag -999 //出错时返回的标志
/*
*栈的实现
*/
typedef struct{
_type *base; //栈底,第一个元素
_type *top; //栈顶,最后一个元素
int size; //栈的大小
}*stack,st;
void InitStack(stack *S); //初始化栈
void DestroyStack(stack *S); //销毁栈
void push(stack st,_type e); //插入元素
_type pop(stack st); //弹出栈顶元素
_type getTop(stack st); //获得栈顶元素,并不删除
int length(stack st); //返回栈的元素个数
int isEmpty(stack st); //是否为空,c语言中没有bool类型
void InitStack(stack *S){
(*S) = (stack)malloc(sizeof(st)); //先为栈的结构体分配空间
(*S)->base = (_type *)malloc( stack_size * sizeof(_type) ); //再为栈里面的数组分配空间
if(!(*S)->base){
printf("malloc failed!");
return;
}
(*S)->top = (*S)->base;
(*S)->size = stack_size;
}
void DestroyStack(stack *S){
_type *temp;
while((*S)->top > (*S)->base){
temp = (*S)->top - 1;
free((*S)->top);
(*S)->top = temp;
}
free((*S)->base);
free(*S);
}
void push(stack st,_type e){
if( (st->top - st->base) >= st->size){
st->base = (_type*)realloc(st->base,(st->size + add_size)*sizeof(_type));
st->size += add_size;
}
if(!st->base){
printf("Remalloc failed!");
return;
}
*st->top++ = e; //equels to *st->top = e; st->top++;
}
_type pop(stack st){
_type e;
if(st->top == st->base)
return endFlag; //Error
e = * --st->top; //equels to st->top--; e=*st->top;
return e;
}
_type getTop(stack st){
if(st->top == st->base)
return endFlag; //Error
return *(st->top-1); //equels to *( (st->top) - 1 );
}
int isEmpty(stack st){
if(length(st) == 0)
return 1;
return 0;
}
int length(stack st){
return st->top - st->base;
}
int main(){
stack st;
int i,e;
InitStack(&st);
for(i = 0;i<10;i++ ){
push(st,i+1);
}
printf("Top is %d,length is %d \n",getTop(st),length(st));
while((e=pop(st)) != endFlag)
{
printf("%d ",e);
}
printf("\n");
DestroyStack(&st);
}
1万+

被折叠的 条评论
为什么被折叠?



