# include# include # include # include typedef struct Node{ int date; struct Node * pNext; } NODE, * pNODE; typedef struct Stack{ pNODE pTop; pNODE pButton; } STACK, * pSTACK; void init_stack(pSTACK); void push_stack(pSTACK, int); bool bool_pop_stack(pSTACK); bool bool_empty_stack(pSTACK); void traverse_stack(pSTACK); void clear_stack(pSTACK); pSTACK create_stack(); int main (void ){ STACK stack; // pSTACK pStack; // pStack = create_stack(); // 可以用 init_stack(&stack); bool_empty_stack(&stack); push_stack(&stack, 1); push_stack(&stack, 2); push_stack(&stack, 3); push_stack(&stack, 4); traverse_stack(&stack); bool_pop_stack(&stack); traverse_stack(&stack); clear_stack(&stack); traverse_stack(&stack); return 0; } pSTACK create_stack(){ pSTACK pStack; pStack = (pSTACK) malloc(sizeof(STACK)); if(pStack->pTop == NULL){ printf("分配失败!n"); exit(-1); }{ printf("分配成功!n"); } pStack->pButton = pStack->pTop; pStack->pButton->pNext = NULL; return pStack; } void init_stack(pSTACK pStack){ pStack->pTop = (pNODE) malloc(sizeof(NODE)); if(pStack->pTop == NULL){ printf("分配失败!n"); exit(-1); } else{ printf("分配成功!n"); } pStack->pButton = pStack->pTop; pStack->pButton->pNext = NULL; } void push_stack(pSTACK pStack, int val){ pNODE pNew = (pNODE) malloc(sizeof(NODE)); pNew->date = val; pNew->pNext = pStack->pTop; pStack->pTop = pNew; } bool bool_empty_stack(pSTACK pStack){ if(pStack->pTop == pStack->pButton){ printf("栈空!n"); return true; }{ return false; } } bool bool_pop_stack(pSTACK pStack){ pNODE p = pStack->pTop; if(bool_empty_stack(pStack)){ printf("栈空,出栈失败!"); return false; } else{ printf("出栈元素:%dn", p->date); } pStack->pTop = p->pNext; free(p); p = NULL; return true; } void traverse_stack(pSTACK pStack){ pNODE p = pStack->pTop; if(p == pStack->pButton){ printf("栈空,无法遍历!n"); } else{ printf("栈中元素:"); } while (p != pStack->pButton){ printf("%d ", p->date); p = p->pNext; } printf("n"); } void clear_stack(pSTACK pStack){ if(bool_empty_stack(pStack)){ printf("栈空,清除失败!n"); return; } else{ printf("清除成功!n"); } pNODE p = pStack->pTop; pNODE q; while (p != pStack->pButton){ q = p->pNext; free(p); p = q; } p = NULL; pStack->pTop = pStack->pButton; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)