源码
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define N 5
typedef struct SNode *Stack;
struct SNode {
int *Data;
int Top;
int MaxSize;
};
Stack CreateStack(int MaxSize)
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Data = (int *)malloc(MaxSize * sizeof(int));
S->Top = -1;
S->MaxSize = MaxSize;
return S;
}
bool IsFull(Stack S)
{
return (S->Top == S->MaxSize - 1);
}
bool Push(Stack S, int X)
{
if (IsFull(S)) {
printf("堆栈满");
return false;
}
else {
S->Data[++(S->Top)] = X;
return true;
}
}
bool IsEmpty(Stack S)
{
return (S->Top == -1);
}
int Pop(Stack S)
{
if (IsEmpty(S)) {
printf("堆栈空");
return ERROR;
}
else
return (S->Data[(S->Top)--]);
}
int StackLength(Stack S)
{
return S->Top + 1;
}
void Stackshow(Stack S)
{
int i=0;
if (-1== S->Top) {
printf("栈是空的");
}else
while (i <= S->Top)
{
printf("%d\t ", S->Data[i++]);
}
printf("\n");
}
int main() {
Stack s;
int i = 0;
s=CreateStack(N);
printf("此时Top指向的元素为%d\n", s->Top);
printf("此时堆栈s的元素有\n");
Stackshow(s);
printf("此时堆栈s的长度为%d\n", StackLength(s));
printf("将元素X压入堆栈\n");
for (i = 1; i < N; i++) {
printf("将%d压入堆栈s\n",i);
Push(s,i);
}
printf("此时Top指向的元素为%d\n", s->Top);
printf("此时堆栈s的元素有\n");
Stackshow(s);
printf("此时堆栈s的长度为%d\n", StackLength(s));
printf("删除并返回栈顶元素\n");
for (i = 1; i < N; i++) {
printf("将%d从堆栈s删除并返回\n", Pop(s));
}
return 0;
}
运行
此时Top指向的元素为-1
此时堆栈s的元素有
栈是空的
此时堆栈s的长度为0
将元素X压入堆栈
将1压入堆栈s
将2压入堆栈s
将3压入堆栈s
将4压入堆栈s
此时Top指向的元素为3
此时堆栈s的元素有
1 2 3 4
此时堆栈s的长度为4
删除并返回栈顶元素
将4从堆栈s删除并返回
将3从堆栈s删除并返回
将2从堆栈s删除并返回
将1从堆栈s删除并返回
|