-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstackar.c
115 lines (99 loc) · 2.47 KB
/
stackar.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "stackar.h"
#include "fatal.h"
#include <stdlib.h>
#define EmptyTOS ( -1 )
#define MinStackSize ( 5 )
struct StackRecord
{
int Capacity;
int TopOfStack;
ElementType *Array;
};
/* START: fig3_48.txt */
int
IsEmpty( Stack S )
{
return S->TopOfStack == EmptyTOS;
}
/* END */
int
IsFull( Stack S )
{
return S->TopOfStack == S->Capacity - 1;
}
/* START: fig3_46.txt */
Stack
CreateStack( int MaxElements )
{
Stack S;
/* 1*/ if( MaxElements < MinStackSize )
/* 2*/ Error( "Stack size is too small" );
/* 3*/ S = malloc( sizeof( struct StackRecord ) );
/* 4*/ if( S == NULL )
/* 5*/ FatalError( "Out of space!!!" );
/* 6*/ S->Array = malloc( sizeof( ElementType ) * MaxElements );
/* 7*/ if( S->Array == NULL )
/* 8*/ FatalError( "Out of space!!!" );
/* 9*/ S->Capacity = MaxElements;
/*10*/ MakeEmpty( S );
/*11*/ return S;
}
/* END */
/* START: fig3_49.txt */
void
MakeEmpty( Stack S )
{
S->TopOfStack = EmptyTOS;
}
/* END */
/* START: fig3_47.txt */
void
DisposeStack( Stack S )
{
if( S != NULL )
{
free( S->Array );
free( S );
}
}
/* END */
/* START: fig3_50.txt */
void
Push( ElementType X, Stack S )
{
if( IsFull( S ) )
Error( "Full stack" );
else
S->Array[ ++S->TopOfStack ] = X;
}
/* END */
/* START: fig3_51.txt */
ElementType
Top( Stack S )
{
if( !IsEmpty( S ) )
return S->Array[ S->TopOfStack ];
Error( "Empty stack" );
return 0; /* Return value used to avoid warning */
}
/* END */
/* START: fig3_52.txt */
void
Pop( Stack S )
{
if( IsEmpty( S ) )
Error( "Empty stack" );
else
S->TopOfStack--;
}
/* END */
/* START: fig3_53.txt */
ElementType
TopAndPop( Stack S )
{
if( !IsEmpty( S ) )
return S->Array[ S->TopOfStack-- ];
Error( "Empty stack" );
return 0; /* Return value used to avoid warning */
}
/* END */