当前位置: 首页 > news >正文

栈(c++)

今天介绍两种在c++中写“栈”方法

1.

#include <bits/stdc++.h>
using namespace std;class mystack {
private:int a[1000];int curr = -1;
public:void push(int);void pop();int top();bool empyt();int size();
};int main()
{mystack n;while(true){int a;cout<<"1.加入元素\n2.删除元素\n3.显示顶端的元素\n4.栈是否为空(1是,0否)\n5.栈的大小\n6.结束"<<endl;cin>>a;if(a==1){int sh;cin>>sh;n.push(sh);}else if(a==2) n.pop();else if(a==3) cout<<n.top()<<endl;else if(a==4) cout<<n.empyt()<<endl;else if(a==5) cout<<n.size()<<endl;else if(a==6) break;system("pause");system("cls");}return 0;
}
void mystack::push(int v)
{if(curr<1000){a[++curr] = v;}else cout<<"栈已满\n";return;
}
void mystack::pop()
{if(curr>-1){curr--;}else cout<<"栈为空\n";return;
}
int mystack::top()
{if(curr>-1) return a[curr];else cout<<"栈为空\n";return -1;
}
bool mystack::empyt()
{if(curr==-1) return true;else return false;
}
int mystack::size()
{return curr+1;
}

2.

​
#include <bits/stdc++.h>
using namespace std;struct node
{int value;node* next;node* prev;node(){}node(int v){value = v;next = NULL;prev = NULL;}
};class mystack {
private:node* root = NULL;node* ptop = NULL;int n = 0;
public:void push(int);void pop();int top();bool empyt();int size();
};int main()
{mystack aaaaa;while(true){int a;cout<<"1.加入元素\n2.删除元素\n3.显示顶端的元素\n4.栈是否为空(1是,0否)\n5.栈的大小\n6.结束"<<endl;cin>>a;if(a==1){int sh;cin>>sh;aaaaa.push(sh);}else if(a==2) aaaaa.pop();else if(a==3) cout<<aaaaa.top()<<endl;else if(a==4) cout<<aaaaa.empyt()<<endl;else if(a==5) cout<<aaaaa.size()<<endl;else if(a==6) break;system("pause");system("cls");}return 0;
}
void mystack::push(int v)
{node* curr = new node(v);if(root==NULL){root = curr;ptop = curr;return;}ptop->next = curr;curr->prev = ptop;ptop = curr;n++;
}
void mystack::pop()
{if(root!=ptop){node* curr = ptop;ptop = ptop->prev;ptop->next = NULL;delete curr;n--;}else if(root==ptop&&root!=NULL){node* curr = ptop;delete curr;n--;root = NULL;ptop = NULL;}else cout<<"栈为空"<<endl;
}
int mystack::top()
{return ptop->value;
}
bool mystack::empyt()
{if(root==NULL)return true;else return false;
}
int mystack::size()
{return n;
}

相关文章:

  • 【java实现+4种变体完整例子】排序算法中【选择排序】的详细解析,包含基础实现、常见变体的完整代码示例,以及各变体的对比表格
  • 【现代深度学习技术】循环神经网络04:循环神经网络
  • ArcGIS及其组件抛出 -- “Sorry, this application cannot run under a Virtual Machine.“
  • 基于 Linux 环境的办公系统开发方案
  • pytorch 51 GroundingDINO模型导出tensorrt并使用c++进行部署,53ms一张图
  • 大数据建模与评估
  • Linux `init 4` 相关命令的完整使用指南
  • Nvidia显卡架构演进
  • 新手记录--从零开始[labelme安装及使用]
  • Ubuntu20.04下Docker方案实现多平台SDK编译
  • 分析虚幻引擎编辑器中使用 TAA 或 TSR 时角色眨眼导致的眼睛模糊问题
  • 【java实现+4种变体完整例子】排序算法中【归并排序】的详细解析,包含基础实现、常见变体的完整代码示例,以及各变体的对比表格
  • 洛谷P1312 [NOIP 2011 提高组] Mayan 游戏
  • 【AI】解决分类问题
  • SICAR 标准 安全门锁操作箱 按钮和指示灯说明
  • 前端vue+后端ssm项目
  • 桌面应用UI开发方案
  • Linux第一个系统程序——进度条
  • UIjavaScritIU
  • 模拟投资大师思维:AI对冲基金开源项目详解
  • 苹果手机为何无法在美制造?全球供应链难迁移
  • 证监会:坚决拥护党中央对王建军进行纪律审查和监察调查的决定
  • 航海王亚洲巡展、工厂店直销……上海多区推出“五五购物节”活动
  • 全国台联原会长杨国庆逝世,享年89岁
  • 湖北鄂城:相继4所小学有学生腹泻呕吐,供餐企业负责人已被采取强制措施
  • 神十九乘组安全顺利出舱