定义栈
typedef struct
{
int a[Size];
int top;
}Stack;
初始化栈
void InitStack(Stack *S)//初始化栈
{
S->top=-1;
}
判空
void Empty(Stack A)//判空
{
if(A.top==-1)
{
printf("Empty.\n");
}
else
printf("Not empty\n");
}
进栈
void Push(Stack *S)//进栈
{
int x;
while(S->top!=Size-1)
{
printf("Stack is not full,please input number:\n");
scanf("%d",&x);
S->a[S->top++]=x;
}
}
出栈
int Pop(Stack *S)//出栈
{
int x;
if(S->top!=-1)
{
x=S->a[S->top--];
}
else
printf("The Stack is empty.\n");
return x;
}
读取栈顶元素
void Gettop(Stack *S)//读取栈顶元素
{
int x;
if(S->top!=-1)
{
x=S->a[S->top];
printf("栈顶元素为:%d\n",x);
}
else
printf("The Stack is empty.\n");
}
销毁栈
void Destory(Stack *S)//销毁栈
{
S->top=-1;
}
在下附上完整代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define Size 3
typedef struct
{
int a[Size];
int top;
}Stack;
void InitStack(Stack *A);//初始化栈
void Empty(Stack A); //判空
void Push(Stack *S);//进栈
void Pop(Stack *S);//出栈
void Gettop(Stack *S);//读取栈顶元素
void Destory(Stack *S);//销毁栈
int main()
{
Stack A;
int x;
InitStack(&A);//初始化栈
Empty(A); //判空
Push(&A);//进栈
Gettop(&A);//读取栈顶元素
x=Pop(&A);//出栈
Destory(&A);
printf("S->top=%d\n",A.top);
Empty(A);
return 0;
}
void InitStack(Stack *S)//初始化栈
{
S->top=-1;
}
void Empty(Stack A)//判空
{
if(A.top==-1)
{
printf("Empty.\n");
}
else
printf("Not empty\n");
}
void Push(Stack *S)//进栈
{
int x;
while(S->top!=Size-1)
{
printf("Stack is not full,please input number:\n");
scanf("%d",&x);
S->a[S->top++]=x;
}
}
int Pop(Stack *S)//出栈
{
int x;
if(S->top!=-1)
{
x=S->a[S->top--];
}
else
printf("The Stack is empty.\n");
return x;
}
void Gettop(Stack *S)//读取栈顶元素
{
int x;
if(S->top!=-1)
{
x=S->a[S->top];
printf("栈顶元素为:%d\n",x);
}
else
printf("The Stack is empty.\n");
}
void Destory(Stack *S)//销毁栈
{
S->top=-1;
}