顺序栈的实现(C语言)

/*
	顺序栈
	VS2010 调试
*/

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

#define TRUE 1
#define FALSE 0

#define STACK_INIT_SIZE 100
#define STACKINCREASEMENT 10

struct SeqStack
{
	int *elem;
	int top;
	int MAXNUM;
};

//初始化栈
int init_seq_stack(struct SeqStack *L)
{
	L->elem = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
	if (!L->elem)
	{
		return 0;
	}

	L->top = 0;
	L->MAXNUM = STACK_INIT_SIZE;

	return 1;
}

/*
函数功能:	判断是否栈满
返 回 值:	0 栈满; 1 栈未满
*/
int is_stack_full(struct SeqStack L)
{
	return (L.top == L.MAXNUM);
}

/*
函数功能:	判断是否栈空
返 回 值:	0 栈空; 1 栈未空
*/
int is_stack_empty(struct SeqStack L)
{
	if (L.top == 0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}

/*
函数功能:	数num 进栈
返 回 值:	0 进栈失败; 1 进栈成功
*/
int push_stack(struct SeqStack *L, int num)
{
	if (is_stack_full(*L))
	{
		return 0;
	}

	L->top++;
	L->elem[L->top] = num;

	return 1;
}

/*
函数功能:	出栈,出栈的数存到x内
返 回 值:	0 失败; 1 成功
*/
int pop_stack(struct SeqStack *L, int *x)
{
	if (!is_stack_empty(*L))
	{
		return 0;
	}

	*x = L->elem[L->top];
	L->top = L->top - 1;

	return 1;
}

/*
函数功能:	取栈顶元素
返 回 值:	栈顶元素值
*/
int get_top_elem(struct SeqStack L)
{
	return L.elem[L.top];
}

/*
函数功能:	打印栈内元素
*/
void print_stack_elem(struct SeqStack L)
{
	int i = 0;
	printf("TOP\n");
	for(i = L.top; i > 0; i--)
	{
		printf("%d\n", L.elem[i]);
	}
	printf("BOTTOM\n");
	printf("\n");
}

/*
函数功能:	将栈置空
*/
void set_empty(struct SeqStack *L)
{
	L->top = 0;
}

/*
函数功能:	销毁栈
*/
int destory_stack(struct SeqStack *L)
{
	if (!L->elem)
	{
		return 0;
	}
	
	free(L->elem);

	return 1;
} 

int main(int argc, char *argv[])
{
	int x = 0;
	struct SeqStack L;

	init_seq_stack(&L);

	push_stack(&L, 7);
	push_stack(&L, 4);
	push_stack(&L, 5);
	push_stack(&L, 8);
	push_stack(&L, 9);
	print_stack_elem(L);

	pop_stack(&L, &x);
	print_stack_elem(L);

	destory_stack(&L);

	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值