栈 - 数组实现
代码如下:
1 #include <cstdio> 2 #include <cstdlib> 3 4 #define EMPTY_STACK (-1) 5 #define MIN_STACK_SIZE (3) 6 7 typedef int itemType; 8 struct Node; 9 typedef struct StackRecord *stack; 10 11 struct StackRecord { 12 int topOfStack; 13 int capacity; 14 itemType *item; 15 }; 16 17 int 18 IsEmpty(stack s) 19 { 20 return s->topOfStack == EMPTY_STACK; 21 } 22 23 int 24 IsFull(stack s) 25 { 26 return s->topOfStack == s->capacity - 1; 27 } 28 29 void 30 Pop(stack s) 31 { 32 if (!IsEmpty(s)) { 33 --s->topOfStack; 34 } 35 } 36 37 itemType 38 Top(stack s) 39 { 40 if (!IsEmpty(s)) { 41 return s->item[s->topOfStack]; 42 } else { 43 printf("Stack is empty!\n"); 44 return -1; 45 } 46 } 47 48 void 49 Push(itemType x, stack s) 50 { 51 if (IsFull(s)) { 52 printf("Out of space!\n"); 53 return; 54 } else { 55 s->item[++s->topOfStack] = x; 56 } 57 } 58 59 void 60 MakeEmpty(stack s) 61 { 62 s->topOfStack = EMPTY_STACK; 63 } 64 65 stack 66 CreateStack(int maxSize) 67 { 68 stack s; 69 70 if (maxSize < MIN_STACK_SIZE) { 71 printf("Stack size is too small!\n"); 72 return NULL; 73 } 74 75 s = (stack)malloc(sizeof(struct StackRecord)); 76 if (s == NULL) { 77 printf("out of space!\n"); 78 return NULL; 79 } 80 81 s->item = (itemType*)malloc(sizeof(itemType) * maxSize); 82 if (s->item == NULL) { 83 printf("out of space!\n"); 84 return NULL; 85 } 86 s->capacity = maxSize; 87 MakeEmpty(s); 88 return s; 89 } 90 91 void 92 DisposeStack(stack s) 93 { 94 if(s != NULL) { 95 free(s->item); 96 free(s); 97 } 98 } 99 100 int 101 main(int argc, char** argv) 102 { 103 stack s; 104 105 s = CreateStack(10); 106 107 Push(2, s); 108 Push(3, s); 109 Push(5, s); 110 Pop(s); 111 Pop(s); 112 printf("%d\n", Top(s)); 113 114 DisposeStack(s); 115 s = NULL; 116 117 system("pause"); 118 return(0); 119 }