【数据结构】栈

stack.h

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

typedef int STDataType;

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

Stack* STCreate();
void STDestroy(Stack* st);

void STPush(Stack* st, STDataType x);
STDataType STPop(Stack* st);
STDataType STTop(Stack* st);
int STSize(Stack* st);
bool STEmpty(Stack* st);

stack.c

#include"Stack.h"

Stack* STCreate()
{
	Stack* st = (Stack*)malloc(sizeof(Stack));
	if (NULL == st)
	{
		perror("malloc failed");
		exit(-1);
	}
	st->a = NULL;
	st->capacity = st->top = 0;
	return st;
}

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

void STPush(Stack* st, STDataType x)
{
	assert(st);
	if (st->capacity == st->top)
	{
		int newcapacity = st->capacity == 0 ? 4 : st->capacity * 2;
		STDataType* temp = (STDataType*)realloc(st->a, sizeof(STDataType) * newcapacity);
		if (NULL == temp)
		{
			perror("realloc failed");
			exit(-1);
		}
		st->a = temp;
		st->capacity = newcapacity;
	}
	st->a[st->top] = x;
	++st->top;
}

STDataType STPop(Stack* st)
{
	assert(st);
	assert(st->top);
	STDataType ret = STTop(st);
	--st->top;
	return ret;
}

STDataType STTop(Stack* st)
{
	assert(st);
	assert(st->top);
	return st->a[st->top - 1];
}

int STSize(Stack* st)
{
	return st->top;
}

bool STEmpty(Stack* st)
{
	return st->top == 0;
}

test.c

#include <stdio.h>

#include"Stack.h"

static void STPrint(Stack* st)
{
	while (!STEmpty(st))
		printf("%d-", STPop(st));
	printf("\n");
}


void test1()
{
	Stack* st1 = STCreate();
	STPush(st1, 4);
	STPush(st1, 3);
	STPush(st1, 2);
	STPush(st1, 1);
	STPop(st1);
	printf("top = %d\n", STTop(st1));
	printf("size = %d\n", STSize(st1));
	STPrint(st1);
	STDestroy(st1);
}

int main()
{
	test1();

	return 0;
}
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伊H

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值