栈的链式存储结构(C语言实现)
生活随笔
收集整理的這篇文章主要介紹了
栈的链式存储结构(C语言实现)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
簡(jiǎn)要
鏈棧就是利用單鏈表作為棧的存儲(chǔ)結(jié)構(gòu),單鏈表的第一個(gè)節(jié)點(diǎn)為棧頂,而最后一個(gè)節(jié)點(diǎn)為棧底,鏈棧既可以帶頭節(jié)點(diǎn)也可以不帶頭節(jié)點(diǎn)。
實(shí)現(xiàn)過(guò)程
實(shí)現(xiàn)代碼
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> using namespace std; typedef int ElemType; typedef struct student {ElemType data;struct student*next; }linkList; /* * *函數(shù)聲明 * */ void pop(linkList*top,ElemType*e); linkList*InitStack(linkList*top); linkList*push(linkList*top,ElemType data); void getTop(linkList*top,ElemType*e); /* * *獲取棧的長(zhǎng)度 * */ int getLength(linkList*top) {linkList*p=top;int n=0;p=top->next;while(p!=NULL){n++;p=p->next;}return n; } /* * *獲取棧頂?shù)脑獥K? * */ void getTop(linkList*top,ElemType*e) {if(!top)cout<<"棧無(wú)效!"<<endl;if(!top->next)cout<<"棧為空!"<<endl;*e=top->next->data;} /* * *初始化棧 * */ linkList*InitStack(linkList*top) {top=(linkList*)malloc(sizeof(linkList));top->next=NULL;return top; } /* * *入棧 * */ linkList*push(linkList*top,ElemType data) {linkList*s=(linkList*)malloc(sizeof(linkList));s->data=data;s->next=top->next;//指向棧頂 top->next=s;//重置棧頂 cout<<s->data<<":"<<"入棧"<<endl;return top; //返回棧頂指針 } /* * *出棧 * */ void pop(linkList*top,ElemType*e) {linkList*p;*e=top->next->data;//保存節(jié)點(diǎn)數(shù)據(jù) p=top->next;//獲取棧頂元素 top->next=p->next;//修改棧頂指針 ,讓它指向后一個(gè)節(jié)點(diǎn),使其成為新的棧頂指針 free(p);//釋放內(nèi)存空間 }/* * *遍歷棧 * */ void print(linkList*top) {linkList*p=top->next;while(p!=NULL){cout<<"元素:"<<p->data<<endl;p=p->next;} } int main() {linkList*top;top=InitStack(top);int chose; cout<<"----------------------------------------"<<endl;cout<<"--------------1.入棧--------------------"<<endl;cout<<"--------------2.出棧--------------------"<<endl;cout<<"--------------3.遍歷棧------------------"<<endl;cout<<"--------------4.獲取棧頂元素------------"<<endl;cout<<"--------------5.獲取棧的長(zhǎng)度------------"<<endl;cout<<"--------------0.退出--------------------"<<endl;cout<<"----------------------------------------"<<endl;do{cout<<endl;cout<<"選擇:";cin>>chose;switch(chose){case 1:ElemType data;cout<<"請(qǐng)輸入入棧的元素,輸入0結(jié)束!"<<endl;cout<<endl;cin>>data;while(data!=0){top=push(top, data);cout<<"輸入:";cin>>data;}break;case 2:ElemType e;pop(top,&e);cout<<e<<"出棧"<<endl;break;case 3:cout<<"全部元素為:"<<endl;print(top);break;case 4:ElemType x;getTop(top,&x);cout<<"棧頂元素為:"<<x<<endl;break;case 5:cout<<"棧的長(zhǎng)度為:"<<getLength(top)<<endl;break;case 0:break;}}while(chose!=0);}運(yùn)行圖片
結(jié)語(yǔ):
整理不易,如果有用,點(diǎn)個(gè)贊,大恩不言謝。
總結(jié)
以上是生活随笔為你收集整理的栈的链式存储结构(C语言实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: RabbitMQ消息队列简单异步邮件发送
- 下一篇: html-列表标签