手搓动态栈

dynamic_array_stack.h

#pragma once
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
typedef int E;
typedef struct {
	E* elements;
	int size;
	int capacity;
}Stack;

Stack* create_stack();
void destroy_stack(Stack* s);

void push_stack(Stack* s, E val);
int pop_stack(Stack* s);
int  peek_stack(Stack* s);
bool is_empty(Stack * s); 

dynamic_array_stack.c

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#include"dynamic_array_stack.h"
#define THRESHOLD 1024
#define default_capacity 10
Stack* create_stack() {
	Stack* stack = malloc(sizeof(Stack));
	if (stack == NULL) {
		printf("ERROR:malloc failed in create_stack\n");
		return NULL;
	}
	stack->size = 0;
	stack->capacity = default_capacity;
	stack->elements = malloc(default_capacity * sizeof(E));
	if (stack->elements = NULL) {
		free(stack);
		printf("ERROR:malloc failed in create_stack");
		return NULL;
	}
	
	
	return stack;
}
void destroy_stack(Stack* s) {
	free(s->elements);
	free(s);
}

void grow_capacity(Stack* s) {
	int new_capacity =
		s->capacity >= THRESHOLD ?
		(s->capacity + (s->capacity >> 1)) :
		(s->capacity << 1);

	E* new_arr = realloc(s->elements, sizeof(E) * new_capacity);
	if (new_arr == NULL) {
		printf("realloc failed in grow_capacity\n");
		exit(1);
	}
	s->elements = new_arr;
	s->capacity = new_capacity;
}

void push_stack(Stack* s, E val) {
	if (s->capacity == s->size) {
		grow_capacity(s);
	}
	s->elements[s->size] = val;
	s->size++;
}
E pop_stack(Stack* s) {
	if (is_empty) {
		printf("ERROR:the stack is empty,pop_stack failed");
		exit(1);
	}
	return s->elements[--s->size];
}
E  peek_stack(Stack* s) {
	if (is_empty) {
		printf("ERROR:the stack is empty,peek_stack failed");
		exit(1);
	}
	return s->elements[s->size-1];
}
bool is_empty(Stack* s) {
	return s->size == 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

后天苦海谈话

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

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

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

打赏作者

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

抵扣说明:

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

余额充值