首页
找靠谱产品
找解决方案
找靠谱公司
找案例
找对的人
专家智库
悬赏任务
SAAS
ToB门户
了解全球最新的ToB事件
论坛
潜水/灌水快乐,沉淀知识,认识更多同行。
ToB圈子
加入IT圈,遇到更多同好之人。
微博
Follow
记录
Doing
博客
Blog
文库
业界最专业的IT文库,上传资料也可以赚钱
下载
分享
Share
排行榜
Ranklist
相册
Album
应用中心
qidao123.com ToB IT社区-企服评测·应用市场
»
论坛
›
数据库
›
Oracle
›
栈(c++)
返回列表
发新帖
栈(c++)
[复制链接]
发表于 2025-9-22 23:47:38
|
显示全部楼层
|
阅读模式
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要
登录
才可以下载或查看,没有账号?
立即注册
×
本日介绍两种在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;
}
复制
代码
回复
使用道具
举报
返回列表
浏览过的版块
DevOps与敏捷开发
Java
物联网
分布式数据库
网络安全
Mysql
祗疼妳一个
+ 我要发帖
登录后关闭弹窗
登录参与点评抽奖 加入IT实名职场社区
去登录
微信订阅号
微信服务号
微信客服(加群)
H5
小程序
快速回复
返回顶部
返回列表