【数据结构】栈的接口的实现(用c语言实现)

  • 栈的概念及结构

  • 栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LFO (Last In First Out)的原则。
  • 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
  • 出栈:栈的删除操作叫做出栈。出数据也在栈顶。
  • 栈的实现

栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。定长的静态栈结构,一般不实用,所以下面给出的是支持动态增长的栈:

具体实现代码如下:

  • <Stack.h>

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

typedef int STDataType;
typedef struct Stack
{
	STDataType* _a;
	int _top;//栈顶
	int _capacity;

}Stack;

void StackInit(Stack* ps, int n);
void StackDestroy(Stack* ps);

void StackPush(Stack* ps, STDataType x);//在栈顶入数据
void StackPop(Stack* ps);//在栈顶出数据

STDataType StackTop(Stack* ps);//取出栈顶的数据

int StackSize(Stack* ps);//返回数据个数
int StackEmpty(Stack* ps);//如果是空 返回0;非空返回1

void StackTest();
  • <Stack.c>

#include "Stack.h"


void StackInit(Stack* ps, int n)
{
	assert(ps);
	ps->_a = (STDataType*)malloc(sizeof(STDataType)*n);
	ps->_top = 0;
	ps->_capacity = n;
}

void StackDestroy(Stack* ps)
{
	
    assert(ps);
    free(ps->_a);
    ps->_a=NULL;
    ps->_top=0;
    ps->_capacity=0;
}

void StackPush(Stack* ps, STDataType x)//在栈顶入数据
{
	assert(ps);
	if (ps->_top == ps->_capacity)//容量检测
	{
		ps->_a = (STDataType*)realloc(ps->_a, ps->_capacity * 2 * sizeof(STDataType));
		ps->_capacity *= 2;
	}
	ps->_a[ps->_top] = x;
	ps->_top++;

}

void StackPop(Stack* ps)//在栈顶出数据
{
	assert(ps);
	if (ps->_top > 0)
	{
		ps->_top--;
	}
}

STDataType StackTop(Stack* ps)//取出栈顶的数据
{
	assert(ps);
	return ps->_a[ps->_top - 1];
}

int StackSize(Stack* ps)//返回数据个数
{
	assert(ps);
	return ps->_top;//top其实就是链表中的size

}

int StackEmpty(Stack* ps)
{
	assert(ps);
	if (ps->_top == 0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
	//return ps->_top == 0 ? 0 : 1;
}
  • <test.c>


#include "Stack.h"


void StackTest()
{
	Stack s;
	StackInit(&s, 3);
	StackPush(&s, 1);
	StackPush(&s, 2);
	StackPush(&s, 3);
	StackPush(&s, 4);
	while (StackEmpty(&s))
	{
		printf("top:%d\n", StackTop(&s));
		StackPop(&s);
	}

}
int main()
{
	StackTest();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42270373/article/details/83033961