一、鏈棧概述
1.為什么要用鏈棧?
鏈式存儲結構可以更好的避免棧上溢,因為順序棧在定義結構體時需要定義最大值。
2.什么是鏈棧
棧的鏈式存儲結構就是鏈棧,棧底就是鏈表的最后一個結點,而棧頂是鏈表的第一個結點,一個鏈??梢杂蓷m斨羔榯op唯一確定。
結構體的定義:
#include<stdio.h>
#include<stdlib.h>
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; //接收數(shù)據(jù)
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("請輸入進棧元素總數(shù):");
scanf("%d",&n);
for(int i=1;i<=n;i++){
printf("請輸入第%d個元素:",i);
scanf("%d",&a);
pushLstack(L,a); //for循環(huán)進棧
}
printf("此時棧序列為:");
printLstack(L); //打印
printf("\n");
popLstack(L); //出棧
popLstack(L); //出棧
printf("\n此時棧序列為:");
printLstack(L); //打印
}
運行結果:
?三、多重鏈棧
?多重鏈棧用到結構體數(shù)組這一個點。
結構體數(shù)組的定義:
1.先聲明結構體,再去定義結構體數(shù)組
struct 結構體名{
成員列表;
};
struct 結構體名 數(shù)組名[長度] ;
2.聲明結構體的同時去定義結構體數(shù)組(結構體名可以省略).
struct 結構體名{
成員列表;
}數(shù)組名[長度];
結構體數(shù)組的引用:
1.變量類型引用。
?通過:結構數(shù)組名[ ].成員變量?? 來進行操作。
struct Day{
int year;
int mouth;
int day;
}stu[2];
Day[1].year=2022;
Day[1].mouth=2;
Day[1].day=7;
2.指針類型。
通過:結構數(shù)組名[ ]->成員變量來操作
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函數(shù)執(zhí)行對于【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); //輸出
}
運行結果:(說明問題即可)文章來源:http://www.zghlxwxcb.cn/news/detail-734665.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-734665.html
到了這里,關于鏈棧(入棧,出棧,遍歷)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!