Data structure-stack implementation (C language version)

Preface

        The stack is a special linear table that only allows insertion and deletion operations at a fixed end. The end where data is inserted and deleted is called the top of the stack, and the other end is called the bottom of the stack. The data elements in the stack follow the last-in-first-out principle.

Table of contents

1. Pushing and popping the stack

2. Implementation of stack

3. Test the code


1. Pushing and popping the stack

        Pushing the stack: The insertion operation of the stack is called pushing the stack, and the input data is on the top of the stack.

        Pop the stack: The deletion operation of the stack is called popping the stack. The outgoing data is also on the top of the stack.

        As shown in the picture:

 

2. Implementation of stack

         //stack.h

#include<stdlib.h>
#include<assert.h>
#include<stdio.h>
#include<stdbool.h>
typedef int SDataType;
typedef struct Stack
{
	SDataType* _a;
	int _top;//栈顶数据
	int _capacity;//容量
}Stack;
void StackInit(Stack* st);//初始化栈
void StackDestory(Stack* st);//销毁栈
void StackPush(Stack* st, SDataType data);//入栈
void StackPop(Stack* st);//出栈

size_t StackSize(Stack* st);//获取栈中元素的数目

SDataType StackTop(Stack* st);//获取栈顶元素

bool StackEmpty(Stack* st);//判断栈是否为空

//stack.c

void StackInit(Stack* st)//初始化栈
{
	st->_a = (SDataType*)malloc(sizeof(SDataType) * 4);
	//申请空间
	//初始化数据
	st->_capacity = 4;
	st->_top = 0;
}
void StackDestory(Stack* st)//销毁栈
{
	free(st->_a);//释放空间
	st->_capacity = st->_top = 0;
}
void StackPush(Stack* st, SDataType data)//入栈
{
	assert(st);//判断指针是否存在

	if (st->_capacity == st->_top)
	{
		//空间满了需要增容
		st->_capacity *= 2;
		SDataType* p = (SDataType *)realloc(st->_a, st->_capacity * sizeof(SDataType));
		if (p == NULL)
		{
			printf("内存不足\n");
			exit(-1);
		}
		st->_a = p;
	}
	st->_a[st->_top] = data;
	++(st->_top);
}
void StackPop(Stack* st)//出栈
{
	assert(st);//确保指针存在
	assert(st->_top > 0);
	--(st->_top);
}
size_t StackSize(Stack* st)//获取栈中元素的数目
{
	assert(st);//确保指针存在
	size_t size = 0;
	return size = st->_top;
}
SDataType StackTop(Stack* st)//获取栈顶元素
{
	return st->_a[(st->_top) -1 ];
}
bool StackEmpty(Stack* st)//判断栈是否为空
{
	return !st->_top;
}

3. Test the code

void TestStack()
{
	Stack st;
	StackInit(&st);
	StackPush(&st, 1);
	StackPush(&st, 2);
	StackPush(&st, 3);
	StackPush(&st, 4);
	StackPush(&st, 5);
	StackPush(&st, 6);
	StackPush(&st, 7);
	StackPush(&st, 8);
	while (!StackEmpty(&st))
	{
		printf("%d ", StackTop(&st));
		StackPop(&st);
	}
	StackDestory(&st);
}

Guess you like

Origin blog.csdn.net/m0_68641696/article/details/132256300