1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <malloc.h> 4 5 typedef struct Node//定义结点 6 { 7 int data; 8 struct Node *pNext; 9 }NODE, *PNODE; 10 11 typedef struct Stack//定义栈,栈相当于一个箱子;共有2个结点,一个表示箱顶一个表示箱底 12 { 13 PNODE pTop;//箱顶 14 PNODE pBottom;//箱底 15 }STACK, *PSTACK; 16 17 void init(PSTACK pS) 18 { 19 pS->pTop = (PNODE)malloc(sizeof(NODE));//先造出一个空栈 20 if (NULL == pS->pTop) 21 { 22 printf("动态内存分配失败!\n"); 23 exit(-1); 24 } 25 else 26 { 27 pS->pBottom = pS->pTop; 28 pS->pBottom->pNext = NULL;//或使用pS->pTop->pNext = NULL 29 //因为他们刚开始指向同一个地方---箱底,只要箱底的指针域为空就行了 30 } 31 } 32 33 void push(PSTACK pS, int val) 34 { 35 PNODE pNew = (PNODE)malloc(sizeof(NODE));//创建一个新的结点放到栈里 36 if (NULL == pNew) 37 { 38 printf("动态内存分配失败!\n"); 39 exit(-1); 40 } 41 42 pNew->data = val; 43 pNew->pNext = pS->pTop; 44 pS->pTop = pNew; 45 46 return; 47 } 48 49 void traverse(PSTACK pS)//遍历输出 50 { 51 PNODE p = pS->pTop;//注意一定要用p临时存放箱顶的结点指针,不然结束后箱顶的结点指针就变了---会影响其他的函数执行 52 53 while (p != pS->pBottom)//当p == pS->pBottom时结束, 此时p已经变成了pS->pBottom箱底 54 { 55 printf("%d ", p->data); 56 p = p->pNext; 57 } 58 putchar(10); 59 60 return; 61 } 62 63 bool empty(PSTACK pS) 64 { 65 if (pS->pTop == pS->pBottom) 66 { 67 return true; 68 } 69 else 70 return false; 71 } 72 //把pS所指向的栈出栈一次,并把出栈的元素存入pVal所指向的变量 73 bool pop(PSTACK pS, int *pVal) 74 { 75 if (empty(pS)) 76 { 77 return false; 78 } 79 else 80 { 81 PNODE r = pS->pTop; 82 *pVal = r->data; 83 pS->pTop = r->pNext; 84 85 free(r); 86 r = NULL; 87 } 88 89 return true; 90 } 91 92 93 void clear(PSTACK pS)//清空--释放内存 94 { 95 if (empty(pS)) 96 return; 97 else 98 { 99 PNODE p = pS->pTop; 100 PNODE q = NULL; 101 102 while (p != pS->pBottom) 103 { 104 q = p->pNext; 105 free(p); 106 p = q;//结束时p(pS->pTop)已经指向了pS->pBottom箱底,但pS->pTop的内容并不是空结点的 107 } 108 109 pS->pTop = pS->pBottom;//所以在清空的时候, 要将pS->pTop的数据域也为空 110 } 111 } 112 113 int main(void) 114 { 115 int val; 116 STACK S; 117 init(&S); 118 119 push(&S, 1); 120 push(&S, 2); 121 push(&S, 3); 122 push(&S, 4); 123 push(&S, 5); 124 traverse(&S); 125 126 pop(&S, &val);//只出栈一次 127 printf("你出栈的结点的数据域存储的数是:%d\n", val); 128 traverse(&S); 129 130 clear(&S); 131 traverse(&S);//没有的话会空一行 132 133 return 0; 134 }
时间: 2024-10-25 15:37:25