数据结构
刘佳瑜*,王越 *, 黄扬* , 张钊*
(淮北师范大学计算机科学与技术学院,安徽 淮北)
*These authors contributed to the work equllly and should be regarded as co-first authors.
🌞欢迎来到数据结构的世界
🌈博客主页:卿云阁💌欢迎关注🎉点赞👍收藏⭐️留言📝
🌟本文由卿云阁原创!
🙏作者水平很有限,如果发现错误,请留言轰炸哦!万分感谢!
目录
🥝栈的逻辑结构
🥥 栈的基本操作
🍇顺序栈
🍈 共享栈
🍉 链栈
🥝栈的逻辑结构
🥥 栈的基本操作
🍇顺序栈
代码实现:
#include<stdio.h> #include<stdlib.h> #define MaxSize 5 typedef int ElemType; typedef struct { ElemType data[MaxSize];int top; //栈顶指针 }SqStack; //栈的初始化 void InitSqStack(SqStack &S) {S.top=-1;} //判栈空 bool StackEmpty(SqStack S) {if(S.top==-1)return true;elsereturn false; } //入栈的操作 bool Push(SqStack &S,ElemType x) {if(S.top==MaxSize-1)return false;S.top++;S.data[S.top]=x; } //出栈的操作 bool Pop(SqStack &S,ElemType &x) {if(S.top==-1)return false;x=S.data[S.top];S.top--; } //打印出栈所有的元素 void print(SqStack &S) {int i=0; printf("此时栈中的所有元素:\n");for(i=0;i<=S.top;i++)printf("%d ",S.data[i]);printf("\n"); } int main() {SqStack S;int x=0; InitSqStack(S);printf("入栈0,1,2,3,4:\n");Push(S,0);Push(S,1);Push(S,2);Push(S,3);Push(S,4);print(S); printf("执行一次出栈:\n");Pop(S,x);print(S); }
🍈 共享栈
🍉 链栈
代码实现:
#include<stdio.h> #include<stdlib.h> #define MaxSize 5 typedef int ElemType; typedef struct Node { ElemType data;struct Node *next; }StackNode,*LinkStack;//栈的初始化 void InitSqStack(LinkStack &top) {top=NULL;} //栈判空 int StackEmpty(LinkStack top) {if(top==NULL)return true;elsereturn false; } //进栈操作 void Push(LinkStack &top,ElemType x) {LinkStack s;s=(LinkStack)malloc(sizeof(StackNode));s->data=x;s->next=top;top=s; } //出栈操作 int Pop(LinkStack &top,ElemType &x) {if(StackEmpty(top))return false;LinkStack p;p=(LinkStack)malloc(sizeof(StackNode));x=top->data;p=top;top=top->next;free(p);return true; } void print(LinkStack top) {LinkStack p;top=top;printf("链栈中的元素:\n");while(top!=NULL) {printf("%d ",top->data);top=top->next; } } int main() {LinkStack top;InitSqStack(top);int x=0;printf("链栈的相关操作:\n");printf("进栈0,1,2,3,4:\n");Push(top,0);Push(top,1);Push(top,2);Push(top,3);Push(top,4);print(top); printf("\n");printf("执行一次出栈:\n");Pop(top,x);print(top); }
Institutional Review Board Statement: Not applicable.
Informed Consent Statement: Not applicable.
Data Availability Statement: Not applicable.
Author Contributions:All authors participated in the assisting performance study and approved the paper.
Conflicts of Interest: The authors declare no conflict of interest.