数据结构:顺序栈

源文件

#include "seq_stack.h"

//创建顺序栈
seq_p create_stack()                       
{
	seq_p S = (seq_p)malloc(sizeof(seq_stack));
	if (S == NULL)
	{
		printf("申请空间失败\n");
		return NULL;
	}
	S->top = -1;  //记录栈中没有元素
	return S;
}

//判空
int empty_stack(seq_p S)
{
	if (S == NULL)
	{
		printf("入参为空\n");
		return -1;
	}
	return S->top == -1 ? 1 : 0;
}

//判满
int full_stack(seq_p S)
{
	if (S == NULL)
	{
		printf("入参为空\n");
		return -1;
	}
	return S->top == MAX - 1 ? 1 : 0;
}

//入栈(只能在栈顶操作)
void push_stack(seq_p S, datatype data)
{
	if (S == NULL)
	{
		printf("入参为空,请检查\n");
		return;
	}
	if (full_stack(S))
	{
		printf("栈已满\n");
		return;
	}
	S->top++;
	S->data[S->top] = data;
}

//输出栈中元素
void show_stack(seq_p S)
{
	if (S == NULL)
	{
		printf("入参为空\n");
		return;
	}
	if (empty_stack(S))
	{
		printf("栈为空\n");
		return;
	}

	//要保留栈只能从栈顶操作的性质
	for (int i = S->top; i >= 0; i--)
	{
		printf("%d\n", S->data[i]);
	}
}

//出栈/弹栈
void pop_stack(seq_p S)
{
	if (S == NULL)
	{
		printf("入参为空\n");
		return;
	}
	if (empty_stack(S))
	{
		printf("栈空无需出栈\n");
		return;
	}
	printf("%d\t",S->data[S->top--]);
}

void clean_stack(seq_p S)
{
	if (S == NULL)
	{
		printf("入参为空\n");
		return;
	}
	S->top = -1;
}

void free_stack(seq_p* S)
{
	if (S == NULL || *S == NULL)
	{
		printf("入参为空\n");
		return;
	}

	//释放堆区空间
	free(*S);
	*S = NULL;
}

头文件

#ifndef SEQ_STACK_H_
#define SEQ_STACK_H_

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

#define MAX  10

typedef int datatype;
typedef struct seq_stack
{
	datatype data[MAX];
	int top;
}seq_stack,*seq_p;

//创建顺序栈
seq_p create_stack();

void free_stack(seq_p* S);

#endif // !SEQ_STACK_H_

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值