1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <stdio.h> #include <stdlib.h> typedef struct Node{ int data; struct Node* pNext; } Node,* PNode;
typedef struct Stack{ PNode pTop; PNode pBottom; } Stack,* PStack;
void init(PStack); void push(PStack,int); void traverse(PStack); void pop(PStack,int*); void clear(PStack); int main() { Stack S; int val; init(&S); push(&S,1); push(&S,2); push(&S,3); push(&S,4); push(&S,5); push(&S,6); traverse(&S); pop(&S,&val); printf("pop的值为%d\n",val); traverse(&S); clear(&S); traverse(&S); return 0; }
void init(PStack pS){ pS->pTop = (PNode)malloc(sizeof(Node)); if(pS == NULL){ printf("分配内存失败!\n"); exit(-1); }else{ pS->pBottom = pS->pTop; pS->pBottom->pNext = NULL; } return; }
void push(PStack pS,int val){ PNode pNew = (PNode)malloc(sizeof(Node)); pNew->data = val; pNew->pNext = pS->pTop; pS->pTop = pNew; return; }
void traverse(PStack pS){ if(pS->pTop == pS->pBottom){ printf("栈为空!\n"); return; }else{ PNode p = pS->pTop; while (p != pS->pBottom) { printf("%d ",p->data); p = p->pNext; } printf("\n"); } return; }
void pop(PStack pS,int* val){ if(pS->pTop == pS->pBottom){ printf("栈为空!\n"); return; }else{ *val = pS->pTop->data; PNode p = pS->pTop; pS->pTop = pS->pTop->pNext; free(p); p = NULL; } return; }
void clear(PStack pS){ if(pS->pTop == pS->pBottom){ printf("栈为空!\n"); return; }else{ PNode p = pS->pTop; PNode q; while (p != pS->pBottom) { q = p; p = p->pNext; free(q); q = NULL; } pS->pTop = pS->pBottom; printf("已clear成功!\n"); return; } }
|