/*
* 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);
}
C语言堆栈实现( 动态数组 )
最新推荐文章于 2024-08-17 16:03:28 发布