#include<stdio.h>
#include<stdbool.h>
//顺序存储,用静态数组实现,需要记录栈顶指针
//定义、初始化(创)、增(进栈)、删(出栈)、判空、查(读栈顶元素)、销
#define maxsize 50//栈中元素的最大个数
//顺序表结构定义
struct sqstack
{
int data[maxsize];
int top;//数组下标,由于是顺序存储也就相当于了指针,这个指的是栈顶指针
};
//初始化顺序栈
void initialize_stack(struct sqstack* s)
{
s->top = -1;
}
//判断栈是否为空
bool empty_stack(struct sqstack s)
{
if(s.top == -1)
{
printf("the stack is empty.\n");
return true;//空栈
}
else
{
printf("the stack is not empty.\n");
return true;//不空
}
}
//增(进栈)
bool push(struct sqstack* s, int x)
{
if(s->top == maxsize - 1)
return false;
else
{
s->top++;
s->data[s->top] = x;
return true;
}
}
//删(出栈)
bool pop(struct sqstack* s)
{
if(s->top == -1)
return false;//栈空了
else
{
int a = s->data[s->top];
printf("被删除的元素是:%d ", a);
s->top--;
return true;
}
}
//查找栈顶元素
bool gettop(struct sqstack s)
{
if(s.top == -1)
{
printf("栈为空的!\n");
return false;
}
else
{
printf("栈顶元素是:%d \n", s.data[s.top]);
return true;
}
}
//打印栈
void print_stack(struct sqstack s)
{
printf("栈");
while(s.top != -1)
{
printf("%d ", s.data[s.top]);
s.top--;
}
printf("\n");
return;
}
int main()
{
struct sqstack s;
initialize_stack(&s);
printf("push 1:");
push(&s, 1);
print_stack(s);
printf("push 2:");
push(&s, 2);
print_stack(s);
printf("push 5:");
push(&s, 5);
print_stack(s);
printf("pop操作");
pop(&s);
print_stack(s);
printf("pop操作");
pop(&s);
print_stack(s);
empty_stack(s);
gettop(s);
return 0;
}
栈——顺序栈的定义以及基本操作 超详细!
最新推荐文章于 2022-04-05 20:00:00 发布