栈
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef int ElementType; 5 6 struct StackNode 7 { 8 ElementType Element; 9 struct StackNode *Next; 10 }; 11 12 int StackIsEmpty(struct StackNode *StackTop) 13 { 14 return (StackTop -> Next == NULL); 15 } 16 17 int StackPush(ElementType ToBePush,struct StackNode *StackTop) 18 { 19 struct StackNode *TmpCell; 20 21 TmpCell = malloc(sizeof(struct StackNode)); 22 if(TmpCell == NULL) 23 { 24 return 1; 25 } 26 else 27 { 28 TmpCell -> Element = ToBePush; 29 TmpCell -> Next = StackTop -> Next; 30 StackTop -> Next = TmpCell; 31 } 32 return 0; 33 } 34 35 ElementType StackGetTop(struct StackNode *StackTop) 36 { 37 if(!StackIsEmpty(StackTop)) 38 { 39 return StackTop -> Next -> Element; 40 } 41 42 return 1; 43 } 44 45 int StackPop(struct StackNode *StackTop) 46 { 47 struct StackNode *FirstCell; 48 49 if(StackIsEmpty(StackTop)) 50 { 51 return 1; 52 } 53 else 54 { 55 FirstCell = StackTop -> Next; 56 StackTop -> Next = StackTop -> Next -> Next; 57 free(FirstCell); 58 } 59 return 0; 60 } 61 62 int MakeStackEmpty(struct StackNode *StackTop) 63 { 64 if(StackTop == NULL) 65 { 66 return 1; 67 } 68 else 69 { 70 while( !StackIsEmpty(StackTop) ) 71 { 72 StackPop(StackTop); 73 } 74 } 75 return 0; 76 } 77 78 struct StackNode *StackInit() 79 { 80 struct StackNode *StackTop; 81 82 StackTop = malloc(sizeof(struct StackNode)); 83 if(StackTop == NULL) 84 { 85 return NULL; 86 } 87 88 StackTop -> Next = NULL; 89 MakeStackEmpty(StackTop); 90 return StackTop; 91 } 92 93 int StackDelete(struct StackNode *StackTop) 94 { 95 if(StackTop == NULL) 96 { 97 return 1; 98 } 99 else 100 { 101 MakeStackEmpty(StackTop); 102 free(StackTop); 103 } 104 return 0; 105 } 106 107 int main() 108 { 109 struct StackNode *StackTop; 110 StackTop = StackInit(); 111 112 StackPush(11,StackTop); 113 StackPush(12,StackTop); 114 StackPush(13,StackTop); 115 int TopEle = StackGetTop(StackTop); 116 printf("%d\n",TopEle); 117 StackPop(StackTop); 118 TopEle = StackGetTop(StackTop); 119 printf("%d\n",TopEle); 120 StackPop(StackTop); 121 StackPop(StackTop); 122 StackPop(StackTop); 123 StackPop(StackTop); 124 StackPop(StackTop); 125 StackPop(StackTop); 126 StackPop(StackTop); 127 StackPop(StackTop); 128 TopEle = StackGetTop(StackTop); 129 printf("%d\n",TopEle); 130 MakeStackEmpty(StackTop); 131 StackPush(1,StackTop); 132 StackPush(2,StackTop); 133 StackPush(3,StackTop); 134 MakeStackEmpty(StackTop); 135 StackDelete(StackTop); 136 return 0; 137 }