本节介绍基本的数据结构:栈。以链式栈为例:
1)基本结构的定义:
typedef struct __stack stack;
typedef struct __node node;
struct __stack
{
node *pNode;
int cursor;
int size;
};
struct __node
{
struct __node *next;
void *p_data;
};
2)基本操作:
/*
* create a stack with initial value data.
*/
stack *create(void)
{
stack *p_stack;
node *p_node;
p_stack = (stack *)malloc(sizeof(stack));
if (p_stack == NULL)
{
perror("create stack failed!\n");
return NULL;
}
p_stack->pNode = NULL;
p_stack->cursor = 0;
p_stack->size = 0;
return p_stack;
}
//destory all node;
int destory_stack(stack *pStack)
{
node *p;
if (pStack == NULL)
return 0;
for (p = pStack->pNode; p != NULL; p = p->next)
{
free(p->p_data);
free(p);
}
free(pStack);
return 0;
}
/*
* Note: old type is pointer to pointer;
*/
#define ADD_NODE(old, new) do \
{ (new)->next = (*old); (*old) = (new); }\
while(0) \
/*
* push;
*/
int push(stack *pStack, void *data)
{
node *p_node;
if (pStack == NULL)
{
perror("stack invalid!\n");
return -1;
}
if (pStack->size >= MAX_NODE)
{
perror("stack over flow!\n");
return -1;
}
p_node = (node *)malloc(sizeof(node));
if (p_node == NULL)
{
perror("push alloc node failed!\n");
return -1;
}
p_node->p_data = (int *)malloc(sizeof(int));
if (p_node->p_data == NULL)
{
perror("push alloc data space error!\n");
free(p_node);
return 1;
}
*(int *)(p_node->p_data) = *(int *)data;
ADD_NODE(&(pStack->pNode), p_node);
pStack->size += 1;
return 0;
}
/*
* pop
*/
int pop(stack *pStack, void *out_data)
{
node *p;
if (pStack == NULL || pStack->size == 0 || pStack->pNode == NULL)
{
//perror("pop stack error!\n");
return -1;
}
p = pStack->pNode;
*(int *)out_data = *(int *)(p->p_data);
pStack->size -= 1;
pStack->pNode = p->next;
free(p->p_data);
free(p);
return 0;
}
3)打印所有节点:
/*
* print out all node's data;
*/
int dump_stack(stack *pStack)
{
#define LINE_NUM 5
node *p = NULL;
int count = 0;
if (pStack == NULL || pStack->size == 0 || pStack->pNode == NULL)
{
//perror("dump stack error!\n");
return -1;
}
p = pStack->pNode;
for ( ; p != NULL; p = p->next, ++ count)
{
if (count != 0 && count % LINE_NUM == 0)
printf("\n");
printf("%d\t", *(int *)(p->p_data));
}
printf("\n");
return 0;
}
至此,栈的简单实现完成。下一节讲述测试及说明。