浅谈栈(Stack)实现
发布日期:2021-05-04 18:21:46 浏览次数:22 分类:精选文章

本文共 1692 字,大约阅读时间需要 5 分钟。

文章目录

Stack概念

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

Stack实现

Stack.h文件

#pragma once#include 
#include
#include
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");}
上一篇:leetcode-有效的括号-26
下一篇:leetcode-最大连续子数组的和-25

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月16日 21时20分20秒