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

栈(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;
}

http://www.xdnf.cn/news/496.html

相关文章:

  • 单例模式:懒汉式的两种优化写法
  • Unity webgl 获取图片或视频数据
  • 【unity】Vulkan模式下部分Android机型使用VideoPlayer组件播放视频异常问题
  • 交易系统的构建与实战法则
  • JCST 2025年 区块链论文 录用汇总
  • 电子电器架构 --- DFMEA设计失效模式和后果分析
  • 聊一聊接口自动化测试脚本如何进行维护的?
  • 齿轮检测中的“正负之谜”:为何有的项目有,有的没有?
  • C# 预定义类型全解析
  • Selenium 入门之环境搭建
  • `Accelerate`库实现模型并行计算
  • SAP系统工艺路线的分配物料出现旧版包材
  • 第6章 类文件结构《深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)》
  • [特殊字符] AI 大模型的 Prompt Engineering 原理:从基础到源码实践
  • Linux | 软件仓库管理
  • 回溯算法(3):番外篇
  • 机器学习决策树
  • GESP2025年3月认证C++八级( 第三部分编程题(2)割裂)
  • ICS丨Chapter 1 Introduction to Computer System
  • C++中chrono计时器的简单使用示例
  • CF1016赛后总结
  • 常见网络问题
  • 2025年第16届蓝桥杯嵌入式竞赛学习笔记(十四):RTC实时时钟
  • 算法--打表法
  • JS案例-基于Proxy的响应式数据
  • [密码学基础]国密算法深度解析:中国密码标准的自主化之路
  • 在已有的vue项目中使用vuex
  • 鸿蒙开发11-ARKUI框架
  • 谷歌称LLMs.txt类似于关键词元标签:SEO影响与应对策略
  • 提升电脑性能!Windows超级管理器,免费使用,功能全面!