数据结构学习 顺序栈的C语言实现

#pragma once

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

typedef int data_t;
typedef struct
{
	data_t* data;//数据类型
	int max_lenth;//栈的最大容量
	int top;//栈顶位置下标

}sqstack, *pstack;

//创建顺序栈,返回结构体sqstack的地址
pstack stack_creat(int lenth);

//入栈操作
int stack_push(pstack p, data_t* val);

//出栈操作,返回出栈元素的值
data_t stack_pop(pstack p);

//打印栈
void stack_show(pstack p);

//清空栈
int stack_clear(pstack p);

//释放动态开辟的空间
int stack_free(pstack p);

头文件stack.h

#include "stack.h"

pstack stack_creat(int lenth)
{
	pstack s;
	s = (pstack)malloc(sizeof(sqstack));
	s->data = (data_t*)malloc(sizeof(data_t) * lenth);
	s->max_lenth = lenth;
	s->top = -1;//栈顶下标为-1时为空栈

	return s;
}

int stack_push(pstack p, data_t* val)
{
	if (p == NULL)
	{
		//printf("Pointer is NULL.\n");
		return -1;
	}
	if (p->top == p->max_lenth - 1)
	{
		//printf("Stack is full.\n");
		return -1;
	}
	(p->top)++;
	*(p->data + p->max_lenth - p->top - 1) = *val;

	return 0;
}

data_t stack_pop(pstack p)
{
	data_t temp;
	if (p == NULL)
	{
		//printf("Pointer is NULL.\n");
		return -1;
	}
	if (p->top == - 1)
	{
		//printf("Stack is empty.\n");
		return -1;
	}
	temp = *(p->data + p->max_lenth - p->top - 1);
	*(p->data + p->max_lenth - p->top - 1) = 0;
	(p->top)--;
	return temp;
}

void stack_show(pstack p)
{
	if (p == NULL)
	{
		//printf("Pointer is NULL.\n");
		return;
	}
	if (p->top == -1)
	{
		printf("Stack is empty.\n");
	}
	int temp = p->top;
	while (p->top != -1)
	{
		printf("%d\t%p\n", *(p->data + p->max_lenth - p->top - 1),
			p->data + p->max_lenth - p->top - 1);
		(p->top)--;
	}
	p->top = temp;
}

int stack_clear(pstack p)
{
	if (p == NULL)
	{
		//printf("Pointer is NULL.\n");
		return -1;
	}
	if (p->top == -1)
	{
		//printf("Stack is empty.\n");
		return -1;
	}
	while (p->top != -1)
	{
		*(p->data + p->max_lenth - p->top - 1) = 0;
		(p->top)--;
	}
	return 0;
}

int stack_free(pstack p)
{
	if (p == NULL)
	{
		//printf("Pointer is NULL.\n");
		return -1;
	}
	free(p->data);
	free(p);
	return 0;
}

函数实现stack.c

#include "stack.h"

int main()
{
	pstack p;
	p = stack_creat(10);

	//test
	for (int i = 0; i < 5; i++)
	{
		stack_push(p, &i);
	}

	stack_show(p);
	printf("##############\n");

	stack_pop(p);

	stack_show(p);
	printf("##############\n");

	stack_clear(p);
	stack_show(p);
	printf("##############\n");

	stack_free(p);
	//
	return 0;
}

测试部分test.c

运行结果

需要注意的是,栈是由高地址向低地址生长的,也就是说栈底是高地址,栈顶是低地址,出栈入栈操作都只能对栈顶进行。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值