1. 程式人生 > >[數據結構與算法] : 棧的數組實現

[數據結構與算法] : 棧的數組實現

and eof void emp ace pac warn rac war

頭文件

 1 typedef int ElementType;
 2 
 3 #ifndef _STACK_AR_
 4 #define _STACK_AR_
 5 
 6 struct StackRecord;
 7 typedef struct StackRecord *Stack;
 8 
 9 int IsEmpty(Stack S);
10 int IsFull(Stack S);
11 Stack CreateStack(int MaxElements);
12 void DisposeStack(Stack S);
13 void MakeEmpty(Stack S);
14 void Push(ElementType X, Stack S); 15 ElementType Top(Stack S); 16 void Pop(Stack S); 17 ElementType TopAndPop(Stack S); 18 19 #endif

源文件

 1 #include "stackar.h"
 2 #include <malloc.h>
 3 #include "fatal.h"
 4 #include <stdlib.h>
 5 
 6 #define EmptyTOS (-1)
 7 #define
MinStackSize (5) 8 9 struct StackRecord 10 { 11 int Capacity; 12 int TopOfStack; 13 ElementType *Array; 14 }; 15 16 int IsEmpty(Stack S) 17 { 18 return S->TopOfStack == EmptyTOS; 19 } 20 21 int IsFull(Stack S) 22 { 23 return S->TopOfStack == S->Capacity - 1
; 24 } 25 26 Stack CreateStack(int MaxElements) 27 { 28 Stack S; 29 30 if(MaxElements < MinStackSize) 31 Error("Stack size is to small!"); 32 33 S = (Stack)malloc( sizeof(struct StackRecord) ); 34 if( S == NULL ) 35 FatalError("Out of Space!"); 36 37 S->Array = (ElementType*)malloc( sizeof(ElementType) * MaxElements ); 38 if(S->Array == NULL) 39 FatalError("Out of Space!"); 40 S->Capacity = MaxElements; 41 MakeEmpty(S); 42 43 return S; 44 } 45 46 void DisposeStack(Stack S) 47 { 48 if(S != NULL) 49 { 50 free(S->Array); 51 free(S); 52 } 53 } 54 55 void MakeEmpty(Stack S) 56 { 57 if(S == NULL) 58 Error("Create stack first!"); 59 else 60 S->TopOfStack = EmptyTOS; 61 } 62 63 void Push(ElementType X, Stack S) 64 { 65 if( IsFull(S) ) 66 Error("Full Srack!"); 67 else 68 S->Array[++S->TopOfStack] = X; 69 } 70 71 ElementType Top(Stack S) 72 { 73 if( IsEmpty(S) ) 74 { 75 Error("Empty Srack!"); 76 return 0; /* return value used to avoid warning */ 77 } 78 else 79 return S->Array[S->TopOfStack]; 80 } 81 82 void Pop(Stack S) 83 { 84 if( IsEmpty(S) ) 85 Error("Empty Srack!"); 86 else 87 --S->TopOfStack; 88 } 89 90 ElementType TopAndPop(Stack S) 91 { 92 if( IsEmpty(S) ) 93 { 94 Error("Empty Srack!"); 95 return 0; /* return value used to avoid warning */ 96 } 97 else 98 return S->Array[S->TopOfStack--]; 99 }

測試文件

 1 #include <stdio.h>
 2 #include "stackar.h"
 3 
 4 main( )
 5 {
 6     Stack S;
 7     int i;
 8 
 9     S = CreateStack( 12 );
10     for( i = 0; i < 10; i++ )
11         Push( i, S );
12 
13     while( !IsEmpty( S ) )
14     {
15         printf( "%d\n", Top( S ) );
16         Pop( S );
17     }
18 
19     DisposeStack( S );
20     return 0;
21 }

[數據結構與算法] : 棧的數組實現