练习了一下数据结构的栈的实现,感悟就是栈的容量好像没有在数据结构中引用。不过最后测试都通过了。还是老习惯,自己的练习自己看,留下来,提供一下参考,我先把数据结构学习一下,再来研究有应用的技术。基础打扎实点再说别的。稳住!
#include <stdio.h>
#include <alloc.h>
typedef struct array_stack
{
int *space;
int top;
int base;
int size;
int volume;
}array_stack;
/**
* visit element method.
*/
void visit(int data)
{
printf("%d\t",data);
}
/**
* init the stack.
*/
void stack_init(array_stack *stack)
{
(*stack).volume=100;
(*stack).space=(int *)malloc(sizeof(int)*(*stack).volume);
(*stack).base=0;
(*stack).top=-1;
(*stack).size=0;
}
/**
* destroy the stack.
*/
void stack_destroy(array_stack *stack)
{
(*stack).base=0;
(*stack).top=-1;
(*stack).size=0;
(*stack).volume=0;
free((*stack).space);
}
/**
* clear the stack.
*/
void stack_clear(array_stack *stack)
{
(*stack).base=0;
(*stack).top=-1;
(*stack).size=0;
}
/**
* jugde the stack is empty.
*/
int stack_empty(array_stack *stack)
{
return (*stack).size==0?1:0;
}
/**
* get the stack length.
*/
int stack_length(array_stack *stack)
{
return (*stack).size;
}
/**
* get the stack top.
*/
int stack_get_top(array_stack *stack)
{
return (*stack).space[(*stack).top];
}
/**
* push a element to the stack.
*/
void stack_push(array_stack *stack,int element)
{
int move_index=(*stack).base;
int *new_space=NULL;
if((*stack).volume == (*stack).size)
{
new_space=(int*)malloc(sizeof(int)*(*stack).volume*2);
for(;move_index< (*stack).size;move_index++)
{
new_space[move_index]=(*stack).space[move_index];
}
free((*stack).space);
(*stack).space=new_space;
(*stack).volume=(*stack).volume*2;
}
(*stack).top++;
(*stack).space[(*stack).top]=element;
(*stack).size++;
}
/**
* pop a element from the stack.
*/
void stack_pop(array_stack *stack,int *element)
{
*element=(*stack).space[(*stack).top];
(*stack).top--;
(*stack).size--;
}
/**
* traverse the stack.
*/
void stack_traverse(array_stack *stack,void (*ptr)(int data))
{
int move_index=(*stack).base;
for(;move_index<=(*stack).top;move_index++)
{
ptr((*stack).space[move_index]);
}
}
int main()
{
int move_index=0;
int pop_data=0;
array_stack test_stack;
stack_init(&test_stack);
stack_traverse(&test_stack,visit);
for(;move_index<300;move_index++)
{
stack_push(&test_stack,move_index);
}
stack_traverse(&test_stack,visit);
stack_pop(&test_stack,&pop_data);
printf("\nthe pop number:%d",pop_data);
printf("\nthe stack is empty ? :%d",stack_empty(&test_stack));
printf("\nthe stack length:%d",stack_length(&test_stack));
printf("\nthe stack top:%d",stack_get_top(&test_stack));
stack_clear(&test_stack);
printf("\n");
stack_traverse(&test_stack,visit);
stack_destroy(&test_stack);
}
数据结构,越写越觉得熟练,理解也更加深刻。