栈的基本操作(初始化,进栈,出栈等)

#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define INITSIZE 100//初始时栈的容量
#define ADDEDSIZE 10//每次新增加的容量
typedef struct
{
    
    
	ElemType* base;
	ElemType* top;
	int stacksize;
}stack;
void InitStack(stack  &S)//初始化
{
    
    
	S.base = (ElemType*)(malloc(INITSIZE * sizeof(int)));
	S.top = S.base;//栈空:top=base 
	S.stacksize = INITSIZE;
}
bool GetTop(stack& S, int& e)//返回栈顶元素
{
    
    
	if (S.top == S.base)
		return false;
	e = *(S.top-1);
	return true;
}
void jinzhan(stack& S, int e)//进栈操作
{
    
    
	if (S.top - S.base >= S.stacksize)//栈满
	{
    
    
		S.base = (ElemType*)(realloc(S.base, (S.stacksize + ADDEDSIZE) * sizeof(ElemType)));//栈满,申请空间,此处使用realloc函数在原有的指针域继续申请空间
		S.top = S.base + S.stacksize;
		S.stacksize += ADDEDSIZE;
	}
	*S.top = e;
	S.top++;
}
bool chuzhan(stack& S, ElemType* e)//出栈操作
{
    
    
	if (S.top == S.base)
		return false;
	S.top--;
	e = S.top;
	return true;
}
int getlength(stack&S)//总长度
{
    
    
	int i;
	i = S.top - S.base;
	return i;
}
bool isEmpty(stack& S)
{
    
    
	if (S.base == S.top)
		return false;
	return true;
}

猜你喜欢

转载自blog.csdn.net/weixin_51235620/article/details/115310633