//顺序栈
#include
"global.h"
#define
STACK_INIT_SIZE
100;
#define
STACKINCRENMENT
10;
typedef
struct
SqStack
{
//相当于表头。 数据区是从base到pop; 存储空间从base到base+stacksize
ElemType
*base;
//在栈构造之前和销毁之后,base的值为NULL
ElemType
*top;
int
stacksize;
//当前已分配的存储空间
}
SqStack
;
Status
InitStack(
SqStack
&
S
)
{
S
.base=(
ElemType
*)malloc(100*
sizeof
(
ElemType
));
if
(!(
S
.base)) exit(
OVERFLOW
);
S
.top=
S
.base;
S
.stacksize=
STACK_INIT_SIZE
;
return
OK
;
}
Status GetTop(
SqStack
S
,
ElemType
&
e
)
{
if
(
S
.top==
S
.base)
//不为空栈
return
ERROR
;
return
*(
S
.top-1);
}
Status
Push(
SqStack
&
S
,
ElemType
e
)
{
if
((
S
.top-
S
.base)>=
S
.stacksize)
//栈满,追加空间
{
ElemType
*newbase=(
ElemType
*)realloc(
S
.base,(
S
.stacksize+10)*
sizeof
(
ElemType
));
if
(!newbase) exit(
OVERFLOW
);
S
.base=newbase;
S
.top=
S
.base+
S
.stacksize;
S
.stacksize=
S
.stacksize+
STACKINCRENMENT
;
}
*
S
.top++=
e
;
return
OK
;
}
Status
Pop(
SqStack
&
S
,
ElemType
&
e
)
{
if
(
S
.base==
S
.top)
return
ERROR
;
e
=*--
S
.top;
return
OK
;
}
bool
StackEmpty(
SqStack
S
)
{
if
(
S
.base>=
S
.top)
return
true
;
return
false
;
}
main()
//Sq_Stack(顺序栈) TEST
SqStack
S;
InitStack(S);
for
(
int
i=0;i<300;i++)
Push(S,i);
ElemType
e;
while
(!StackEmpty(S))
{
Pop(S,e);
printf(
"%4d"
,e);
if
(e%10==0)
printf(
"\n\n"
);
}