栈的数组实现
声明 cursor_stack.h:
1 #ifndef CURSOR_STACK_H_INCLUDED 2 #define CURSOR_STACK_H_INCLUDED 3 struct StackRecord; 4 typedef struct StackRecord *Stack; 5 6 int IsEmpty(Stack S); 7 int IsFull(Stack S); 8 Stack CreateStack(int MaxElements); 9 void DisposeSatck(Stack S); 10 void MakeEmpty(Stack S); 11 void Push(int X, Stack S); 12 int Top(Stack S); 13 void Pop(Stack S); 14 int TopAndPop(Stack S); 15 16 #endif // CURSOR_STACK_H_INCLUDED
实现 implementation.c:
1 #include<stdio.h> 2 #include "cursor_stack.h" 3 #define EmptyTOS -1 4 #define MinStackSize 5 5 6 struct StackRecord{ 7 int Capacity; 8 int TopOfStack; 9 int *Array; 10 }; 11 12 Stack CreateStack( int MaxElements) { 13 Stack S; 14 if(MaxElements < MinStackSize) 15 printf("Stack Too Small!"); 16 S = malloc(sizeof(struct StackRecord)); 17 if(S == NULL) 18 printf("Out of space!"); 19 S->Array = malloc(sizeof(int) * MaxElements); 20 if(S->Array == NULL) 21 printf("Out of space!"); 22 S->Capacity = MaxElements; 23 MakeEmpty(S); 24 return S; 25 } 26 27 void MakeEmpty(Stack S) { 28 S->TopOfStack = EmptyTOS; 29 } 30 31 int IsEmpty(Stack S) { 32 return S->TopOfStack == EmptyTOS; 33 } 34 35 void Push(int X, Stack S) { 36 if(IsFull(S)){ 37 printf("Full Stack!\n"); 38 } 39 else { 40 S->Array[++S->TopOfStack] = X; 41 } 42 } 43 44 int Top(Stack S) { 45 if(!IsEmpty(S)) 46 return S->Array[S->TopOfStack]; 47 } 48 49 void Pop(Stack S) { 50 if(IsEmpty(S)) 51 printf("Empty Stack"); 52 else{ 53 S->TopOfStack--; 54 } 55 } 56 57 int TopAndPop(Stack S) { 58 if(!IsEmpty(S)){ 59 return S->Array[S->TopOfStack--]; 60 } else { 61 return 0; 62 } 63 } 64 65 int IsFull(Stack S) { 66 return S->TopOfStack == S->Capacity - 1; 67 }
测试 main.c:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include "cursor_stack.h" 4 5 int main() 6 { 7 Stack S; 8 S = CreateStack(100); 9 int i = 0; 10 for(; i < 100; i++){ 11 Push(i, S); 12 } 13 printf("%d ", Top(S)); 14 Push(i, S); 15 printf("%d ", Top(S)); 16 Pop(S); 17 printf("%d", Top(S)); 18 return 0; 19 }
浙公网安备 33010602011771号