Stack.h

#pragma once
#define N 3
typedef int SDataType;
//动态栈
typedef struct Stack
{
	SDataType*_array;
	int _capacity;//有效元素的最大个数
	int _top;//栈顶
}Stack;


void StackInit(Stack*ps);//栈的初始化
void _Checkcapacity(Stack*ps);//检测容量
void StackPush(Stack*ps, SDataType data);//压栈(在栈顶插入数据data)
void StackPop(Stack*ps);//出栈(在栈顶弹出数据data)
SDataType StackTop(Stack*ps);//取栈顶元素
int StackSize(Stack*ps);//获取栈中有效元素的个数
int StackEmpty(Stack*ps);//检测栈是否为空
void StackDeatory(Stack*ps);//销毁栈
void StackPrint(Stack*ps);//打印

Stack.c

#include"Stack.h"
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

//栈的初始化
void StackInit(Stack*ps)
{
	assert(ps);
	ps->_array = (SDataType*)malloc(sizeof(SDataType)*N);
	if (ps->_array == NULL)
	{
		exit(1);
	}
	ps->_capacity = N;
	ps->_top = 0;
}

void _Checkcapacity(Stack*ps)
{
	//若空间已满,则进行扩容
	if (ps->_top == ps->_capacity)
	{
		int New_capacity = ps->_capacity * 2;
		ps->_array = (SDataType*)realloc(ps->_array, sizeof(SDataType)*New_capacity);
		if (ps->_array == NULL)
		{
			exit(1);
		}
		ps->_capacity = New_capacity;
	}
}


//压栈(在栈顶插入数据data)
void StackPush(Stack*ps, SDataType data)
{
	assert(ps);
	_Checkcapacity(ps);
	ps->_array[ps->_top] = data;
	ps->_top++;
}

//出栈(在栈顶弹出数据data)
void StackPop(Stack*ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	/*if (ps->_top == 0)
	{
		return;
	}*/
	ps->_top--;
}


//取栈顶元素
SDataType StackTop(Stack*ps)
{
	assert(ps);
	//若栈为空
	assert(!StackEmpty(ps));
	//栈不为空
	return ps->_array[ps->_top-1];
}




//获取栈中有效元素的个数
int StackSize(Stack*ps)
{
	assert(ps);
	return ps->_top;
}




//检测栈是否为空(为空返回1,不为空返回0)
int StackEmpty(Stack*ps)
{
	assert(ps);
	return ps->_top == 0;
}




//销毁栈
void StackDeatory(Stack*ps)
{
	assert(ps);
	free(ps->_array);
	ps->_capacity = 0;
	ps->_top = 0;
}
//打印
void StackPrint(Stack*ps)
{
	assert(ps);
	for (int i = 0; i < ps->_top; i++)
	{
		printf("%d ", ps->_array[i]);
	}
	printf("\n");
}

test.c

#include"Stack.h"
#include<stdio.h>
#include<stdlib.h>
void test()
{
	Stack s;
	StackInit(&s);
	StackPush(&s, 1);
	StackPush(&s, 2);
	StackPush(&s, 3);
	StackPush(&s, 4);
	StackPush(&s, 5);
	StackPrint(&s);

	StackPop(&s);
	StackPop(&s);
	StackPop(&s);
	StackPop(&s);
	StackPop(&s);


	StackDeatory(&s);
	//StackPrint(&s);



	int size = StackSize(&s);
	printf("size=%d\n", size);

	/*int ret = StackTop(&s);
	printf("ret=%d\n", ret);*/
	/*StackPush(&s, 4);
	StackPush(&s, 5);
	StackPush(&s, 6);*/
}


int main()
{

	test();
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值