栈这里的一些有关栈的基本操作∵没有涉及结构指针的指针和动态内存管理的内容∴相较于之前学习的链表难度有大幅度的降低,所以这里记录一下学习的原码。不过值得一提的是,栈这里有个知识点是共享栈,这个想法比较有趣,适合玩味。
//
// main.c
// 栈_顺序栈_创销增删改查
//
// Created by 郭宸羽 on 31/7/2022.
//
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 10
typedef struct SqStack {
int data[MaxSize];//静态数组
int top;//栈顶指标 ⇔ top ⇔ 数组下标
}SqStack;//Sq ⇔ sequence ⇔ 顺序
//初始化:
void IniStack(SqStack *S)
{
S->top=-1;
}
int stackEmpty(SqStack S)
{
if(S.top==-1)
return 1;
else
return -1;
}
int StackFull(SqStack S)
{
if(S.top == MaxSize )
return 1;
else
return -1;
}
int Push(SqStack *S,int element_data)
{
if(S->top == MaxSize-1)//判断栈顶指引是否等于栈顶
{
printf("该栈已满,无法压栈,请重新操作。\n");
return -1;
}
else
S->data[++S->top]=element_data;
return 1;
}
int Pop(SqStack *S)
{
int pop_element;
if(S->top > -1 && S->top < MaxSize)//栈的顶索引范围应为[0,MaxSize-1]
{
printf("pop element: [%d]\n",S->data[S->top]);
pop_element = S->data[S->top--];//逻辑上删除栈顶元素,物理上并没有。⚠️top-- 先使用top的值再将top-1
return 1;
}
else
{
printf("This stack's pop has failure,please check and retry");
return -1;
}
}
void DisPlay(SqStack S)
{
printf("Display Stack:\n");
while (S.top < MaxSize&& S.top>-1)
{
printf("[%d]\n",S.data[S.top]);
if(S.top == 0)
{
printf("\n");
return;
}
else
{
printf(" |\n");
printf(" v\n");
S.top--;
}
}
printf("\n");
}
int main()
{
SqStack S;
IniStack(&S);
Push(&S, 1);
Push(&S, 10);
Push(&S, 100);
Push(&S, 1000);
Push(&S, 10000);
Push(&S, 1000);
Push(&S, 100);
Push(&S, 10);
Push(&S, 1);
Push(&S, 1234);
Pop(&S);
DisPlay(S);
return 1;
}