海风游戏狂欢季-独家活动首发平台

堆栈(顺序栈)的创建,栈满与栈空判断,入栈,出栈等操作(C语言)
2025-11-30 06:37:37

目录

一、堆栈的结构体定义

二、堆栈的操作

1.创建一个空栈

2.栈满与栈空判断

3.入栈操作

4.出栈操作

一、堆栈的结构体定义

//重命名,可根据不同的存储元素随时更改

typedef int ElementType;

typedef int Position;

typedef struct SNode *PtrToNode;

struct SNode{

Position top;//确定栈顶位置

ElementType *data;//利用数组存储元素

int MaxSize;//栈容量

};

typedef PtrToNode Stack;

二、堆栈的操作

1.创建一个空栈

// 创建堆栈

Stack CreateStack(int MaxSize){

Stack S = (Stack)malloc(sizeof(struct SNode));

S->data = (ElementType*)malloc(sizeof(ElementType) * MaxSize);//申请元素内存空间

S->top = -1;//初始化栈顶位置

S->MaxSize = MaxSize;//初始化栈容量

return S;

}

2.栈满与栈空判断

// 判断栈满

bool IsFull(Stack S){

return (S->top == S->MaxSize - 1);

}

// 判断栈空

bool IsEmpty(Stack S){

return (S->top == -1);

}

3.入栈操作

// ERROR通过define自定义,设定ERROR值为-1

// 入栈

bool Insert(Stack S, ElementType data){

if(!IsFull(S)){

S->data[++(S->top)] = data;

printf("%d", S->top);

return true;

}

else{

printf("栈满!!!");

return ERROR;

}

}

4.出栈操作

// 出栈

ElementType Pop(Stack S){

if(!IsEmpty(S)){

return S->data[(S->top)--];

}

else{

printf("栈空!!!");

return ERROR;

}

}

全部代码如下:

#include

#include

#include

#define ERROR -1

typedef int ElementType;

typedef int Position;

typedef struct SNode *PtrToNode;

struct SNode{

Position top;

ElementType *data;

int MaxSize;

};

typedef PtrToNode Stack;

// 创建堆栈

Stack CreateStack(int MaxSize){

Stack S = (Stack)malloc(sizeof(struct SNode));

S->data = (ElementType*)malloc(sizeof(ElementType) * MaxSize);

S->top = -1;

S->MaxSize = MaxSize;

return S;

}

// 判断栈满

bool IsFull(Stack S){

return (S->top == S->MaxSize - 1);

}

// 判断栈空

bool IsEmpty(Stack S){

return (S->top == -1);

}

// 出栈

ElementType Pop(Stack S){

if(!IsEmpty(S)){

return S->data[(S->top)--];

}

else{

printf("栈空!!!");

return ERROR;

}

}

// 入栈

bool Insert(Stack S, ElementType data){

if(!IsFull(S)){

S->data[++(S->top)] = data;

printf("%d", S->top);

return true;

}

else{

printf("栈满!!!");

return ERROR;

}

}

int main(){

int MaxSize;

scanf("%d", &MaxSize);

Stack S = CreateStack(MaxSize);

ElementType data;

// 入栈

while(1){

scanf("%d", &data);

if(!IsFull(S)){

Insert(S, data);

}

else{

printf("栈满,无法入栈!!!");

break;

}

}

// 出栈

while(1){

// 注意,堆栈元素中不能出现-1,如果出现,那么出栈之后将进入下面if判断从而跳出循环!!!

ElementType res = Pop(S);

if(res == ERROR){

break;

}

else{

printf("%d ", res);

}

}

return 0;

}

如有错误,欢迎批评指正!!!

盗窃罪160万判刑几年
ipad怎么导入照片
最新文章