#define _CRT_SECURE_NO_WARNINGS 1
//顺序栈
#include <stdio.h>
#include <stdlib.h>
#define ok 1
#define error 0
#define MAXSIZE 100
typedef struct
{
int data[MAXSIZE];
int top;
}SqStack;
//初始化
void InitStack(SqStack* S)
{
S->top = -1;
}
//进栈
int Push(SqStack* S)
{
if (S->top == MAXSIZE - 1) return error;
int e;
scanf("%d", &e);
S->top++;
S->data[S->top] = e;
return ok;
}
//返回栈顶
int GetStack(SqStack* S, int* e)
{
if (S->top == -1) return error;
*e = S->data[S->top];
return ok;
}
//出栈
int Pop(SqStack* S,int *e)
{
if (S->top == -1) return error;
*e = S->data[S->top];
S->top--;
return ok;
}
//栈的长度
int StackLength(SqStack* S,int *e)
{
if (S->top == -1) return error;
*e = S->top + 1;
return ok;
}
//清空栈
int ClearStack(SqStack* S)
{
S->top = -1;
return ok;
}
int main()
{
SqStack S;
int n,i,e;
InitStack(&S);
printf("请输入进栈个数: ");
scanf("%d", &n);
printf("\n请输入进栈的元素: ");
for (i = 0; i < n; i++)
{
Push(&S);
}
printf("栈顶元素是: ");
if (GetStack(&S, &e))
{
printf("%d\n", e);
}
else printf("此栈为空栈!!!\n");
printf("栈的长度为: ");
if (StackLength(&S, &e))
{
printf("%d\n", e);
}
else printf("此栈为空栈!!!\n");
printf("请输入出栈元素个数: ");
scanf("%d", &n);
printf("\n出栈元素有:\n");
for (i = 0; i < n; i++)
{
Pop(&S, &e);
printf("%d ", e);
}
printf("\n栈顶元素是: ");
if (GetStack(&S, &e))
{
printf("%d\n", e);
}
else printf("此栈为空栈!!!\n");
if (ClearStack(&S))
{
printf("栈已清空!!!\n");
}
return 0;
}
数据结构--顺序栈
于 2023-07-16 21:07:35 首次发布