C语言堆栈实现( 动态数组 )

/*
 * stack.h
 *
 *  Created on: 2011-10-7
 *      Author: Admin
 */

#ifndef STACK_H_
#define STACK_H_
#include <stdio.h>
#include <stdlib.h>

/* the data type of stack's data area in stack */
typedef int Data;

typedef struct _stack{
	size_t length;		/* the length of stack */
	size_t capacity;	/* the capacity of stack */
	Data *data;			/* the data that contained in stack */
}Stack, *pStack;

/* initialize stack */
void stack_init(pStack* ptr, size_t size);

/* free stack */
void stack_destory(pStack* ptr);

/* add data to stack */
int stack_push(pStack ptr, Data val);

/* pop from the stack */
Data stack_pop(pStack ptr);

/* return the size of stack */
int stack_size(pStack ptr);

void print_stack(pStack ptr);

#endif /* STACK_H_ */


/*
 * Stack.c
 *
 *  Created on: 2011-10-7
 *      Author: Admin
 */
#include "Stack.h"
#include <stdio.h>


void stack_init(pStack* ptr, size_t size){

	*ptr = (pStack)malloc(sizeof(Stack));

	if ((*ptr) == NULL){
		exit(1);
	}

	(*ptr)->capacity = size;

	(*ptr)->data = (Data*)malloc( sizeof(Data) * ((*ptr)->capacity) );

	if ((*ptr)->data == NULL){
		exit(1);
	}

	(*ptr)->length = 0;
}

/* initialize stack */
void stack_destory(pStack* ptr){

	free((*ptr)->data);
	(*ptr)->data = NULL;
	free((*ptr));
	*ptr = NULL;
}

/* add data to stack */
int stack_push(pStack ptr, Data val){

	if (ptr->length >= ptr->capacity){
		return 0;
	}
	ptr->data[ptr->length] = val;
	ptr->length += 1;
	return 1;
}

/* pop from the stack */
Data stack_pop(pStack ptr){
	if (ptr->length <= 0){
		exit(1);
	}
	ptr->length -= 1;
	return ptr->data[ptr->length];
}

/* return the size of stack */
int stack_size(pStack ptr){
	return ptr->length;
}

void print_stack(pStack ptr){
	int i = 0;
	for (i = 0; i < ptr->length; i++){

		printf("%d ", ptr->data[i]);
	}
	printf("\n%d\n", i);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值