简化版 栈的C++实现及栈的函数模板
来源:互联网 发布:c语言数组初值 编辑:程序博客网 时间:2024/06/05 18:02
学数据结构,每个人第一次接触的恐怕都是栈,当然我也不例外。记得当年啥都不会编,只会照着书上代码抄,结果满是bug。。
今天,有了大学两年多的积淀,终于可以用自己的理解和体会来写栈的内部实现,最后也实现了一个函数模板,也就是栈内元素类型可以根据用户的输入而动态的变化。
虽然几乎每一个C++编译器中都封装了stack.h的头文件,只要包含这个头文件,就可以调用栈。实际的比赛和项目中也是这样用。但是我还是想自己实现一遍,巩固自己写到的知识,而且还可以给后来的初学者提供一个最简化的栈的版本。
#include <iostream>using namespace std;class stack{public: stack(); bool empty(); bool full(); int get_top(); void pop(); void push(int a);public: int data[100]; int count;};stack::stack(){ count = 0;}bool stack::empty(){ if(count == 0) return true; else return false;}bool stack::full(){ if(count == 100) return true; else return false;}int stack::get_top(){ if(!empty()){ return data[count-1]; } else return -1000; //表示出错}void stack::pop(){ if(!empty()) count--;}void stack::push(int a){ if(!full()){ data[count] = a; count ++; }}int main(){ stack s; for(int i=0;i<5;i++){ s.push(i); } cout<<endl; while(!s.empty()){ cout<<s.get_top()<<" "; s.pop(); } return 0;}
#include <iostream>using namespace std;template <class T>class stack{public: stack(); bool empty(); bool full(); T get_top(); void pop(); void push(T a);public: T data[100]; int count;};template <class T>stack<T>::stack(){ count = 0;}template <class T>bool stack<T>::empty(){ if(count == 0) return true; else return false;}template <class T>bool stack<T>::full(){ if(count == 100) return true; else return false;}template <class T>T stack<T>::get_top(){ if(!empty()){ return data[count-1]; } else return -1000; //表示出错}template <class T>void stack<T>::pop(){ if(!empty()) count--;}template <class T>void stack<T>::push(T a){ if(!full()){ data[count] = a; count ++; }}int main(){ stack<int> s; for(int i=0;i<5;i++){ s.push(i); } cout<<endl; while(!s.empty()){ cout<<s.get_top()<<" "; s.pop(); } //使用double类型 stack<double> s1; s1.push(1.2); s1.push(2.3); s1.push(1.5); cout<<endl; while(!s1.empty()){ cout<<s1.get_top()<<" "; s1.pop(); } return 0;}
0 0
- 简化版 栈的C++实现及栈的函数模板
- 【C】变长参数表及printf函数简化版的实现
- 栈(stack)的模板类及成员函数的实现
- [c++]栈模板的实现
- 栈的简介及C++模板实现
- C++:栈(stack)的模板类实现
- C的宏定义实现模板函数——C的C++模板函数机制实现
- 【c语言】用可变参数列表实现一个简化的printf函数
- 在 C 语言中实现模板函数的方法
- 在 C 语言中实现模板函数的方法
- 【转】在C语言中实现模板函数的方法
- 在c语言中实现函数模板的例子
- 在 C 语言中实现模板函数的方法
- 栈模板的实现
- 使用typedef简化函数指针的声明及定义
- 简化版的SHA1算法C语言版
- c语言模拟实现栈的模板化
- [数据结构]栈的实现(c++/类模板)
- JAVA线程 -- wait notify notifyAll
- JAVA可变参数
- Unity移动游戏优化解决方案--前篇
- Dialog.hide() or Dialog.dismiss()?
- 这么晚才来开通博客,out了
- 简化版 栈的C++实现及栈的函数模板
- The APR based Apache Tomcat Native library which allows optimal performance in production 问题的解决
- 微信第三方登录集成
- MySQL存储过程调试工具
- 理解iOS7的Multipeer Connectivity框架
- Java新特性
- PAT (Basic Level) Practise (中文)1052. 卖个萌 (20)
- Jdbc常用操作总结
- 算法四 第一章第一节基础习题