1链栈
1.1栈结点结构体定义
typedef struct student
{char name[32];char sex;int age;
}DATA_TYPE;
typedef struct stack_node
{DATA_TYPE data;struct stack_node *pnext;
}STACK_NODE;
1.2栈顶结点结构体定义
typedef struct stack_top
{STACK_NODE *ptop;int clen;
}STACK_TOP;
1.3创建栈顶结点
STACK_TOP *create_stack_top(void)
{STACK_TOP *stack_top=NULL;stack_top=malloc(sizeof(STACK_TOP));if(NULL==stack_top){perror("fail to malloc");return NULL;}stack_top->ptop=NULL;stack_top->clen=0;return stack_top;
}
1.4创建栈结点
STACK_NODE *create_stack_new_node(DATA_TYPE data)
{STACK_NODE *stack_node=NULL;stack_node=malloc(sizeof(STACK_NODE));if(NULL==stack_node){perror("fail to malloc");return NULL;}stack_node->data=data;stack_node->pnext=NULL;return stack_node;
}
1.5判断非空栈
int is_empty_stack(STACK_TOP *pstack)
{return NULL==pstack->ptop;
}
1.6入栈
int push_stack(STACK_TOP *pstack,STACK_NODE *pnode)
{if(is_empty_stack(pstack)){pstack->ptop=pnode;}else{pnode->pnext=pstack->ptop;pstack->ptop=pnode;}pstack->clen++;return 0;
}
1.7出栈
1.8遍历栈
void stack_for_each(STACK_TOP *pstack,void (*pfun)(STACK_NODE *))
{STACK_NODE *ptmp=NULL;ptmp=pstack->ptop;while(1){if(NULL==ptmp){break;}pfun(ptmp);ptmp=ptmp->pnext;}
}
void show_data(STACK_NODE *pnode)
{printf("%-10s\t%-10c\t%-10d\n",pnode->data.name,pnode->data.sex,pnode->data.age);
}