一:数组实现
#define MaxSize 10
typedef struct
{
int Data[MaxSize];
int Top;
}Stack;
void Push(Stack *Ptrs,int item)
{
if(Ptrs->Top==MaxSize-1)
{
printf("堆栈满");
return;
}
else
{
Ptrs->Data[++(Ptrs->Top)]=item;
return;
}
}
int Pop(Stack *Ptrs)
{
if(Ptrs->Top==-1)
{
printf("堆栈空");
return ERROR;
}
else
{
return (Ptrs->Data[(Ptrs->Top)--]);
}
}
二:链表实现
typedef struct Node
{
int Data;
struct Node *Next;
}LinkStack;
LinkStack *Top;
LinkStack *CreateStack()
{
LinkStack *S;
S=(LinkStack *)malloc(sizeof(struct Node));
S->Next=NULLl
return S;
}
int IsEmpty(LinkStack *S)
{
return (S->Next==NULL)
}
void Push(int item,LinkStack *S)
{
struct Node *TmpCell;
TmpCell=malloc(sizeof(struct Node));
TmpCell->Data=item;
TmpCell->Next=S->Next;
S->Next=TmpCell;
}
int Pop(LinkStack *S)
{
struct Node *FirstCell;
int TopElem;
if(IsEmpty(S))
{
printf("堆栈空");
return NULL;
}
else
{
FirstCell=S->Next;
S->Next=FirstCell->Next;
TopElem=FirstCell->Data;
free(FirstCell);
return TopElem;
}
}
初学数据结构之堆栈
最新推荐文章于 2022-10-15 20:18:19 发布