- 数组实现
typedef struct{
ElementType Data[MaxSize];
int Top;
}Stack;
void Push( Stack *PtrS, ElementType item )
{
if ( PtrS->Top == MaxSize-1 )
{
printf(“堆栈满”); return;
}
else
{
PtrS->Data[++(PtrS->Top)] = item;
return;
}
}
ElementType Pop(Stack *PtrS)
{
if ( PtrS->Top == -1 )
{
printf(“堆栈空”);
return ERROR;
}
else
return ( PtrS->Data[(PtrS->Top)--]);
}
- 链表实现
typedef struct Node{
ElementType Data;
struct Node *Next;
}LinkStack;
LinkStack *Top;
LinkStack *CreateStack()
{
LinkStack *S;
S =(LinkStack *)malloc(sizeof(struct Node));
S->Next = NULL;
return S;
}
int IsEmpty( LinkStack *S )
{
return ( S->Next == NULL );
}
void Push( ElementType item, LinkStack *S )
{
struct Node *TmpCell;
TmpCell=(LinkStack *)malloc(sizeof(struct Node));
TmpCell->Element = item;
TmpCell->Next = S->Next;
S->Next = TmpCell;
}
ElementType Pop( LinkStack *S )
{
struct Node *FirstCell;
ElementType TopElem;
if( IsEmpty( S ) )
{
printf(“堆栈空”);
return NULL;
}
else
{
FirstCell = S->Next;
S->Next = FirstCell->Next;
TopElem = FirstCell ->Element;
free(FirstCell);
return TopElem;
}
}