浅谈Stack实现

文章目录

Stack概念

  栈是一种特殊的线性表,其中只允许在固定的一端进行插入和删除元素操作的一端称为栈顶,另一端称为栈底。遵循LIFO(last in first out)原则。

Stack实现

Stack.h文件

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

typedef int SLDataType;
typedef struct SeqList
{
	SLDataType* a;
	int top;
	int capacity;
}Stack;

//栈的初始化
void StackInit(Stack* pst);
//栈的销毁
void StackDestory(Stack* pst);
//增加栈顶元素
void StackPush(Stack* pst, SLDataType x);
//移除栈顶元素
void StackPop(Stack* pst);
//返回栈中元素的数目
int StackSize(Stack* pst);
//返回栈顶元素
SLDataType StackTop(Stack* pst);
//栈内判空
int StackEmpty(Stack* pst);

Stack.c文件

#include "Stack.h"

//栈的初始化
void StackInit(Stack* pst)
{
	assert(pst);

	pst->a = (SLDataType*)malloc(sizeof(SLDataType)* 4);
	pst->top = 0;
	pst->capacity = 4;
}

//栈的销毁
void StackDestory(Stack* pst)
{
	assert(pst);

	free(pst->a);
	pst->a = NULL;
	pst->top = pst->capacity = 0;
}

//增加栈顶元素
void StackPush(Stack* pst, SLDataType x)
{
	assert(pst);

	if (pst->top == pst->capacity)
	{
		SLDataType* tmp = realloc(pst->a, pst->capacity * 2 * sizeof(SLDataType));
		if (tmp == NULL)
		{
			printf("relloc fail\n");
			exit(-1);
		}
		pst->a = tmp;
		pst->capacity *= 2;
	}
	pst->a[pst->top] = x;
	pst->top++;
}

//移除栈顶元素
void StackPop(Stack* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));

	pst->top--;
}

//返回栈中元素的数目
int StackSize(Stack* pst)
{
	assert(pst);

	return pst->top;
}

//返回栈顶元素
SLDataType StackTop(Stack* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));
	return pst->a[pst->top - 1];
}

//栈内判空
int StackEmpty(Stack* pst)
{
	assert(pst);

	return pst->top == 0 ? 1 : 0;
}

Test.c

#include "Stack.h"

int main()
{
	Stack st;
	StackInit(&st);
	StackPush(&st, 1);
	StackPush(&st, 2);
	StackPush(&st, 3);
	StackPush(&st, 4);

	while (!StackEmpty(&st))
	{
		printf("%d ", StackTop(&st));
		StackPop(&st);
	}
	printf("\n");
}

猜你喜欢

转载自blog.csdn.net/weixin_43580319/article/details/114367833