【数据结构】—— 支持动态增长的栈

栈的相关概念

  • 栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

栈

栈的相关接口

接 口功 能
void StackInit(Stack* ps);栈的初始化
void StackDestory(Stack* ps);栈的销毁
void StackPush(Stack* ps,STDataType x);从栈顶插入元素,即入栈
void StackPop(Stack* ps);从栈顶删除元素,即出栈
STDataType StackTop(Stack* ps);取栈顶元素
int StackEmpty(Stack* ps);判栈空
int StackSize(Stack* ps);求栈中元素的个数
void StackPrint(Stack* ps);打印栈中元素
void StackTest();测试栈的相关接口

栈的源码

栈的相关接口介绍Stack.h

#pragma once
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>


// 支持动态增长的栈
typedef int STDataType;

typedef struct Stack
{
	STDataType* _array;
	int _top;//栈顶
	int _capacity;//容量
}Stack;

void StackInit(Stack* ps);
void StackDestory(Stack* ps);

void StackPush(Stack* ps,STDataType x);
void StackPop(Stack* ps);
STDataType StackTop(Stack* ps);

int StackEmpty(Stack* ps);
int StackSize(Stack* ps);

void StackPrint(Stack* ps);

void StackTest();

栈的相关接口的实现Stack.c

#define _CRT_SECURE_NO_WARNINGS
#include"Stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	ps->_array = NULL;
	ps->_capacity = ps->_top = 0;
}
void StackDestory(Stack* ps)
{
	assert(ps);
	free(ps->_array);
	ps->_array = NULL;
	ps->_capacity = 0;
	ps->_top = 0;
}

void StackPush(Stack* ps, STDataType x)
{
	assert(ps);
	if (ps->_top == ps->_capacity)
	{
		size_t newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
		ps->_array = (STDataType*)realloc(ps->_array, sizeof(STDataType)*newcapacity);
		assert(ps->_array);
		ps->_capacity = newcapacity;
	}
	ps->_array[ps->_top] = x;
	++ps->_top;   

}
void StackPop(Stack* ps)
{
	assert(ps && ps->_top > 0);
	--ps->_top;
}
STDataType StackTop(Stack* ps)
{
	assert(ps && ps->_top > 0);
	return ps->_array[ps->_top -1];
}

int StackEmpty(Stack* ps)
{
	assert(ps);
	return ps->_top == 0 ? 0 : 1;
}
int StackSize(Stack* ps)
{
	assert(ps);
	return ps->_top;
}

void StackPrint(Stack* ps)
{
	assert(ps);
	while (StackEmpty(ps))
	{
		printf("%d ", StackTop(ps));
		StackPop(ps);
	}
	printf("\n");
}
void StackTest()
{
	Stack s;
	StackInit(&s);
	StackPush(&s, 1);
	StackPush(&s, 2);
	StackPush(&s, 3);
	StackPush(&s, 4);

	printf("%d\n", StackTop(&s));
	printf("%d\n", StackEmpty(&s));
	printf("%d\n", StackSize(&s));

	StackPrint(&s);
	StackDestory(&s);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值