数据结构-栈结构

Stack.h

#pragma once
#include 
#include 
#include 
#include 
#include 
typedef int STDataType;

typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

void STInit(ST* pst);//初始化一个栈
void STDestory(ST* pst);//销毁一个栈
void STPush(ST* pst, STDataType x);//入栈
void STPop(ST* pst);//出栈
STDataType STTop(ST* pst);//获取栈顶元素
bool STEmpty(ST* pst);//判空
int STSize(ST* pst);

Stack.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"

void STInit(ST* pst)
{
	assert(pst);//如果指针为空,无法通过动态申请进行初始化,因为参数为一级指针。
	pst->a = NULL;
	pst->top = 0;
	pst->capacity = 0;
}

void STDestroy(ST* pst)
{
	assert(pst);
	free(pst->a);
	pst->a = NULL;
	pst->capacity = 0;
	pst->top = 0;
}

void STPush(ST* pst,STDataType a)
{
	if (pst->top == pst->capacity)
	{
		int newCapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity;
		STDataType* tmp = (STDataType*)realloc(pst->a, newCapacity * sizeof(STDataType));
		if (tmp == NULL)
		{
			perror("realloc fail::");
			return;
		}
		pst->a = tmp;
		pst->capacity = newCapacity;
	} 
    pst->a[pst->top] = a;
	pst->top += 1;
}

void STPop(ST* pst)
{
	assert(pst);
	assert(!STEmpty(pst));
	pst->top--;
}


STDataType STTop(ST* pst)
{
	assert(pst);
	assert(!STEmpty(pst));
	return pst->a[pst->top - 1];
}

bool STEmpty(ST* pst)
{
	assert(pst);
	/*if (pst->top == 0)
		return true;
	else return false;
	*/
	return pst->top == 0;
}

int STSize(ST* pst)
{
	assert(pst);
	return pst->top;
}

test.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"
int main()
{
	ST st;
	STInit(&st);
	STPush(&st, 0);
	STPush(&st, 7);
	STPush(&st, 2);
	STPush(&st, 0);
	//STPrint (&st);栈和队列不能这样写个打印函数进行访问。
	//打印时要一边出栈一边打印,但是这样访问完后就会丢失数据。
	while (!STEmpty(&st))
	{
		printf("%d ",STTop(&st));
		STPop(&st);
	}
	return 0;
}

你可能感兴趣的:(数据结构,算法,c++)