堆栈只能后进先出。 我的理解是一个特殊的链表,只能在链表头部进行插入和删除,其他位置不能更改。
顺序栈的基本代码:
typedef int Position
;
struct SNode
{
ElementType
*Data
;
Position Top
;
int MaxSize
;
};
typedef struct SNode
*Stack
;
Stack
CreateStack( int MaxSize
)
{
Stack S
= (Stack
)malloc(sizeof(struct SNode
));
S
->Data
= (ElementType
*)malloc(MaxSize
* sizeof(ElementType
));
S
->Top
= -1;
S
->MaxSize
= MaxSize
;
return S
;
}
bool
IsFull( Stack S
)
{
return (S
->Top
== S
->MaxSize
-1);
}
bool
Push( Stack S
, ElementType X
)
{
if ( IsFull(S
) ) {
printf("堆栈满");
return false
;
}
else {
S
->Data
[++(S
->Top
)] = X
;
return true
;
}
}
bool
IsEmpty( Stack S
)
{
return (S
->Top
== -1);
}
ElementType
Pop( Stack S
)
{
if ( IsEmpty(S
) ) {
printf("堆栈空");
return ERROR
;
}
else
return ( S
->Data
[(S
->Top
)--] );
}
链栈的基本代码
typedef struct SNode
*PtrToSNode
;
struct SNode
{
ElementType Data
;
PtrToSNode Next
;
};
typedef PtrToSNode Stack
;
Stack
CreateStack( )
{
Stack S
;
S
= (Stack
)malloc(sizeof(struct SNode
));
S
->Next
= NULL;
return S
;
}
bool IsEmpty
( Stack S
)
{
return ( S
->Next
== NULL );
}
bool
Push( Stack S
, ElementType X
)
{
PtrToSNode TmpCell
;
TmpCell
= (PtrToSNode
)malloc(sizeof(struct SNode
));
TmpCell
->Data
= X
;
TmpCell
->Next
= S
->Next
;
S
->Next
= TmpCell
;
return true
;
}
ElementType
Pop( Stack S
)
{
PtrToSNode FirstCell
;
ElementType TopElem
;
if( IsEmpty(S
) ) {
printf("堆栈空");
return ERROR
;
}
else {
FirstCell
= S
->Next
;
TopElem
= FirstCell
->Data
;
S
->Next
= FirstCell
->Next
;
free(FirstCell
);
return TopElem
;
}
}
转载请注明原文地址: https://lol.8miu.com/read-10926.html