【问题描述】
栈采用链式存储,编程实现读取、进栈、出栈等基本操作。
3条回答 默认 最新
- CSDN专家-link 2023-03-16 10:28关注
相当于前插法
/* 链栈 实现操作: *1 进栈 *2 出栈 *3 读栈顶元素 *4 判空 代码使用不带头结点的单链表实现链栈, 入栈、出栈操作相当于单链表在表头的 插入、删除操作。 */ #include <iostream> #include <cstdio> using namespace std; typedef int ElemType; struct Node { ElemType data; //栈中元素 Node* next; //下一个元素的指针 }; typedef Node* LinkStack; //初始化一个链栈 void InitLinkStack( LinkStack& S ) { //S永远指向栈顶元素,初始化时栈为空,S初始化为NULL S = NULL; } //判空 bool StackEmpty( LinkStack S ) { if( S == NULL ) return true; return false; } //进栈:将元素x压入堆栈 bool Push( LinkStack& S, ElemType x ) { Node* temp = new Node; temp->data = x; if( S == NULL ) { S = temp; S->next = NULL; return true; } temp->next = S; S = temp; return true; } //出栈:将栈顶元素出栈,并将其值用x带回 bool Pop( LinkStack& S, ElemType& x ) { if( S == NULL ) return false; x = S->data; Node* toFree = S; S = S->next; //新栈顶 delete toFree; return true; } bool GetTop( LinkStack S, ElemType x ) { if( S == NULL ) return false; x = S->data; return true; } void test1() { LinkStack S; InitLinkStack(S); for( int i=1; i<=50; i++ ) { if( Push(S,i) ) { cout << "入栈成功,入栈的元素是:" << i << endl; } else cout << "入栈失败 " << endl; } cout << "-------------------------------" << endl; while( !StackEmpty(S) ) { int x = 0; Pop(S,x); cout << x << endl; } } int main() { test1(); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
- ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
- ¥15 gdf格式的脑电数据如何处理matlab
- ¥20 重新写的代码替换了之后运行hbuliderx就这样了
- ¥100 监控抖音用户作品更新可以微信公众号提醒
- ¥15 UE5 如何可以不渲染HDRIBackdrop背景
- ¥70 2048小游戏毕设项目
- ¥20 mysql架构,按照姓名分表
- ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
- ¥15 delphi webbrowser组件网页下拉菜单自动选择问题