一、数组实现
#include "stacking.h"
typedef int Position;
typedef struct SNode *Stack;
struct SNode {
ElementType *Data; // 存储元素的数组
Position Top; // 栈顶指针
int MaxSize; // 堆栈最大容量
};
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 PtrS, ElementType item)
{
if (PtrS->Top == MaxSize-1) {
printf("堆栈满");
return false;
}
else {
PtrS->Data[++(PtrS->Top)] = item;
return true;
}
}
bool IsEmpty(Stack S)
{
return (S->Top == -1);
}
ElementType Pop(Stack PtrS)
{
if ( PtrS->Top == -1 ) {
printf("堆栈空");
return ERROR; // ERROR是ElementType的特殊值,标志错误
} else
return (PtrS->Data[(PtrS->Top)--]);
}
二、链表实现
#include <stdio.h>
typedef struct SNode *Stack;
struct SNode{
ElementType Data;
struct SNode *Next;
}
Stack CreateStack()
{ // 构建一个堆栈的头结点,返回指针
Stack S;
S = (Stack)malloc(sizeof(struct SNode));
S->Next = NULL;
return S;
}
bool IsEmpty(Stack S)
{ // 判断堆栈s是否为空,若为空函数返回true,否则返回false
return ( S->Next == NULL );
}
bool Push(ElementType item, Stack S)
{ // 将元素X压入堆栈S
struct SNode *TmpCell;
TmpCell = (struct SNode *)malloc(sizeof(struct SNode));
TmpCell->Element = item;
TmpCell->Next = S->Next;
S->Next = TmpCell;
return true;
}
ElementType Pop(Stack S)
{
struct SNode *FirstCell;
ElementType TopElem;
if ( IsEmpty( S ) ) {
printf("堆栈空"); return NULL;
}
else {
FirstCell = S->Next;
S->Next = FirstCell->Next;
TopElem = FirstCell->Data;
free(FirstCell);
return TopElem;
}
}