链栈(入栈,出栈,遍历)

您所在的位置:网站首页 栈的入栈和出栈代码 链栈(入栈,出栈,遍历)

链栈(入栈,出栈,遍历)

2023-08-24 10:17| 来源: 网络整理| 查看: 265

一、链栈概述 1.为什么要用链栈?

链式存储结构可以更好的避免栈上溢,因为顺序栈在定义结构体时需要定义最大值。

2.什么是链栈

栈的链式存储结构就是链栈,栈底就是链表的最后一个结点,而栈顶是链表的第一个结点,一个链栈可以由栈顶指针top唯一确定。

结构体的定义: #include #include typedef struct Stack{ int data; struct Stack *next; }*LStack; 二、基本操作 //初始化链栈 int Init(LStack &top){ top=(Stack *)malloc(sizeof(Stack)); if(top==NULL){ printf("申请内存失败\n"); return -1; } top->next=NULL; return 1; } //入栈 int pushLstack(LStack &top,int e){ LStack s; s=(Stack *)malloc(sizeof(Stack)); //申请结点 if(s==NULL){ printf("申请失败!"); return -1; } s->data=e; //接收数据 s->next=top->next; //类似尾插链表 top->next=s; return 1; } //出栈 int popLstack(LStack &top){ LStack p; if(top->next==NULL){ printf("栈空!"); return 0; } p=top->next; top->next=p->next; printf("%d出栈\n",p->data); free(p); return 1; } //打印栈 int printLstack(LStack top){ if(top==NULL){ printf("栈空!\n"); return 0; } LStack p=top->next; while(p){ printf("%d ",p->data); p=p->next; } } int main(){ LStack L; Init(L); //初始化 int n,a; printf("请输入进栈元素总数:"); scanf("%d",&n); for(int i=1;i成员变量来操作

typedef struct Stack{ int data; struct Stack *next; }*LStack; struct Stack *top[3]; top[?]->next=? top[?]->data=? 多重链表操作: //多重入栈 void pushs( Stack *top[3],int i,int x){ //i 代表要对哪一个栈进行入栈,x 是输入的值 Stack *p=(Stack *)malloc(sizeof(Stack)); p->data=x; p->next=top[i]->next; top[i]->next=p; } //多重出栈 void pops( Stack *top[3],int i){ if(top[i]->next==NULL){ printf("栈空!"); } Stack *p=top[i]->next; top[i]->next=p->next; printf("%d出栈 ",p->data); free(p); } //打印栈 int prints( Stack *top[3],int i){ if(top[i]==NULL){ printf("栈空!\n"); return 0; } LStack p=top[i]->next; while(p){ printf("%d ",p->data); p=p->next; } } //main函数执行对于【1】栈的操作,其他的同理 int main(){ LStack top[3]; //声明 Init(top[3]); //初始化 pushs(&top[3],1,1); //1栈进 1-3 pushs(&top[3],1,2); pushs(&top[3],1,3); printf("\n此时1栈的序列为:"); prints(&top[3],1); //输出 printf("\n"); pops(&top[3],1); //1栈出栈 printf("\n此时1栈的序列为:"); prints(&top[3],1); //输出 }

运行结果:(说明问题即可)



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3