您好,欢迎来到暴趣科技网。
搜索
您的当前位置:首页数据结构 ----- 栈(代码)

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

来源:暴趣科技网
#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);
}

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoquwan.com 版权所有 湘ICP备2024080961号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务