前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数据结构 ----- 栈(代码)

数据结构 ----- 栈(代码)

作者头像
meihuasheng
发布2021-03-18 11:08:17
2890
发布2021-03-18 11:08:17
举报
文章被收录于专栏:phpcodersphpcodersphpcoders
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ERROR 0
#define OK 1 
#define STACKSIZE 10;              //存储空间分配增量
#define STACK_INIT_SIZE 100;    //存储空间初始分配量

typedef int ElemType;
typedef int Status;

typedef struct
{
	ElemType* base;    //栈底
	ElemType* top;     //栈顶
	int stacksize;          //当前已分配的空间
}SqStack;

//初始化一个栈
Status initStack(SqStack &S)
{
	S.base = (ElemType *)malloc(100 * sizeof(ElemType));
	if (!S.base)
	{
		exit(0);
	}
	S.top = S.base;
	S.stacksize = 100;
	return OK;

}

//入栈操作
Status Push(SqStack& S, ElemType e)
{
	if (S.top - S.base >= S.stacksize)   //如果栈满就追加空间
	{                           //新增内存空间
		S.base = (ElemType*)realloc(S.base, (S.stacksize + 10) * sizeof(ElemType));
		if (!S.base) exit(0);
		S.top = S.base + S.stacksize;
		S.stacksize += 10;
	}
	*S.top++ = e;
	return OK;
}

//出栈操作
Status Pop(SqStack& S, ElemType &e)
{
	if (S.top == S.base) return ERROR;
	e = *--S.top;
	return OK;
}

//展示栈所有元素
Status Show(SqStack &S)
{
	int e;
	while (S.top != S.base)
	{
		Pop(S, e);
		printf("元素有%d\n", e);
	}
	return OK;
}




int main()
{
	SqStack S;
	int e;
	initStack(S);
	Push(S, 1);
	Push(S, 2);
	Push(S, 3);
	Push(S, 4);
	Push(S, 5);
	Push(S, 6);
	Pop(S, e);
	printf("%d\n", e);
	Pop(S, e);
	printf("%d\n", e);
	Show(S);
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-10-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档