标签:
声明 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 #define MinStackSize 5 2 3 struct StackRecord{ 4 int Capacity; 5 int TopOfStack; 6 int *Array; 7 }; 8 9 Stack CreateStack( int MaxElements) { 10 Stack S; 11 if(MaxElements < MinStackSize) 12 printf("Stack Too Small!"); 13 S = malloc(sizeof(struct StackRecord)); 14 if(S == NULL) 15 printf("Out of space!"); 16 S->Array = malloc(sizeof(int) * MaxElements); 17 if(S->Array == NULL) 18 printf("Out of space!"); 19 S->Capacity = MaxElements; 20 MakeEmpty(S); 21 return S; 22 } 23 24 void MakeEmpty(Stack S) { 25 S->TopOfStack = EmptyTOS; 26 } 27 28 int IsEmpty(Stack S) { 29 return S->TopOfStack == EmptyTOS; 30 } 31 32 void Push(int X, Stack S) { 33 if(IsFull(S)){ 34 printf("Full Stack!\n"); 35 } 36 else { 37 S->Array[++S->TopOfStack] = X; 38 } 39 } 40 41 int Top(Stack S) { 42 if(!IsEmpty(S)) 43 return S->Array[S->TopOfStack]; 44 } 45 46 void Pop(Stack S) { 47 if(IsEmpty(S)) 48 printf("Empty Stack"); 49 else{ 50 S->TopOfStack--; 51 } 52 } 53 54 int TopAndPop(Stack S) { 55 if(!IsEmpty(S)){ 56 return S->Array[S->TopOfStack--]; 57 } else { 58 return 0; 59 } 60 } 61 62 int IsFull(Stack S) { 63 return S->TopOfStack == S->Capacity - 1; 64 }
测试 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 }
标签:
原文地址:http://www.cnblogs.com/zsdvvb/p/4831749.html