栈-顺序表实现

/***********************************************************************
*Copyright (c)
*Others:注意malloc(0*sizeof(int))的问题
***********************************************************************/

#include <stdio.h>
#include <stdlib.h>

struct SequentialStack
{
	int* date;        /*数据域*/
	int top;          /*date[top]指向栈顶元素,栈为空时,top=-1*/
	int stacksize;    /*栈空间的大小*/
};

typedef struct SequentialStack SqStack;
typedef SqStack* SSp;

/***********************************************************************
*0.错误函数
***********************************************************************/
void Error(char* s)
{
	printf("%s\n",s);
}

/***********************************************************************
*1.初始化栈
***********************************************************************/
void InitSequentialStack(SSp p,int n)
{
	p->date=(int*)malloc(n*sizeof(int));
	p->top=-1;
	p->stacksize=n;
}

/***********************************************************************
*2.销毁栈
***********************************************************************/
void DestroySequentialStack(SSp p)
{
	p->top=-1;
	p->stacksize=0;
	free(p->date);
}


/***********************************************************************
*3.求栈长
***********************************************************************/
int LengthSequentialStack(SSp p)
{
	return p->top + 1;
}


/***********************************************************************
*4.取栈顶元素
***********************************************************************/
int GetTopLengthSequentialStack(SSp p)
{
	if(p->top != -1)
	{
		return p->date[p->top];
	}
	else
	{
		Error("Stack Empty!");
		return 0;
	}
}

/***********************************************************************
*5.入栈
***********************************************************************/
void PushSequentialStack(SSp p,int x)
{
	if((p->top + 1) >= (p->stacksize))
	{
		Error("Stack Overflow!");
	}
	else
	{
		p->top = p->top + 1;
		p->date[p->top] = x;
	}
}


/***********************************************************************
*6.出栈
***********************************************************************/
int PopSequentialStack(SSp p)
{
	if((p->top) >= 0)
	{
		int x = p->date[p->top];
		p->top = p->top - 1;
		return x;
	}
	else
	{
		Error("Stack Empty!");
		return 0;
	}
}


/***********************************************************************
*7.依次弹出栈中所有元素
***********************************************************************/
void PrintPopSequentialStack(SSp p)
{
	int i = p->top;
	printf("栈内元素如下:");
	while(i >= 0)
	{
		printf("%d ",p->date[i]);
		i = i -1;
	}
	printf("\n输出完毕\n\n");
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值