【C语言 数据结构】栈的极简实现

/**
*结构体SqStack作为栈
*SqStack由三部分组成  base是作为栈的底指针  top指向栈顶元素上面的空间 StackSize是栈的大小
*@hqweay 
*/ 


#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
#define OK 1
#define NO 2
typedef int ElemType;
typedef int boolean;

struct SqStack{
	ElemType *base;
	ElemType *top;
	int StackSize;
};

//初始化
boolean InitStack(SqStack *list){
		(*list).base= (ElemType *)malloc(sizeof(ElemType) * STACK_INIT_SIZE);
		if(!((*list).base)){
			printf("分配空间失败\n");
			return NO;
		}
		/**
		*一开始令top指向栈底
		*因为一个元素都没有......... 
		*/
	(*list).top = (*list).base;
	(*list).StackSize = STACK_INIT_SIZE;
	printf("初始化成功");
	return OK;
} 

//入栈
boolean Push(SqStack *list, ElemType e){
		/**
		*入栈首先判断栈是否满了
		*若满了 需要给栈增加空间 
		*/
		if((*list).top - (*list).base >= (*list).StackSize){
		printf("栈满。。。。\n将增加栈的容量\n");
		(*list).base = (ElemType *)realloc((*list).base, ((*list).StackSize + STACKINCREMENT) * sizeof(ElemType));
			if(!((*list).base)){
			printf("分配空间失败\n");
			return NO;
		}
		/**重新分配空间后的栈的top 与 StackSize改变 
		*虽说如此
		* 意义是不变的 
		*/
		(*list).top = (*list).base + (*list).StackSize;
		(*list).StackSize += STACKINCREMENT;
	}
	/**
	*入栈成功 
	*top 指向下一块空间 
	*/
	*((*list).top)++ = e;	
	printf("入栈成功\n");
	return OK;
}

//出栈
boolean Pop(SqStack *list, ElemType *temp){
	if((*list).base == NULL){
		printf("没有数据\n");
	}else{
		(*temp) =*((*list).top - 1);
		(*list).top--;
	}
}

//清空栈
/**
*清空栈,栈仍存在
*只是数据清空
*与销毁栈区分.......... 
*/
boolean ClearStack(SqStack *list){
	(*list).top = (*list).base;
	return OK;
}

//销毁栈
boolean DestroyStack(SqStack *list){
	free((*list).base);
	(*list).base = NULL;
	(*list).top = (*list).base;
	(*list).StackSize = 0;
	return OK;
}

//判断栈是否为空
boolean isEmpty(SqStack list){
	if(list.base != NULL){
		return OK;
	}else{
		return NO;
	}
}

//返回栈顶元素 
boolean GetTop(SqStack list, ElemType *temp){
	if(!isEmpty(list)){
		printf("抱歉  没有元素哦....\n");
		return NO;
	}else{
		*temp = *(list.top - 1);
	}
	return OK;
} 

//遍历栈
boolean StackTraverse(SqStack list){
		if(!isEmpty(list)){
		printf("抱歉  没有元素哦....\n");
		return NO;
	}else{
	ElemType *p = list.base;
	int i = 1;
	while(p != list.top + 1){
		printf("第%d个元素是%d\n", i++, (*p));
		p++;
	}
	}
	return OK;
}

int StackLength(SqStack list){
	ElemType *p = list.base;
	int length = 1;
	while(p != list.top + 1){
		length++;
		p++;
	}
	return length-1;
}
int main(){
	SqStack List;
	ElemType e = 11;
	ElemType temp;
	InitStack(&List);
  Push(&List, 2);
  Push(&List, 1);
  Push(&List, 4);
  Push(&List, 5);
  Push(&List, 7);
  
  Pop(&List, &temp);
  printf("%d", temp); 
  StackTraverse(List);
  
  printf("栈总元素为%d个\n", StackLength(List));
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值