C++ 实现栈
来源:互联网 发布:java最新商城源码 编辑:程序博客网 时间:2024/06/05 14:07
利用数组实现栈,用的是动态数组,直接上代码:
头文件:
class MyStack{public:MyStack(int Capacity);~MyStack(void);int IsEmpty();int IsFull();void Push(int x);void Pop();int Top();private:int capacity;//the capacity of stack.int* myArray;int topOfStack;//the top of stack.};
.cpp文件:
#include "StdAfx.h"#include "MyStack.h"#include <iostream>#include <stdexcept>using std::cin;using std::cout;using std::endl;using std::runtime_error;MyStack::MyStack(int Capacity):topOfStack(-1){/*if(Capacity<5){Error("Stack size is too small");}*/while(Capacity<5){cout<<"Stack size is too small,please enter it again"<<endl;}capacity = Capacity;myArray = new int[size_t(Capacity)];if(myArray==NULL){runtime_error("Out of space");}}MyStack::~MyStack(void){delete [] myArray;}int MyStack::IsEmpty(){return topOfStack == -1;}int MyStack::IsFull(){return topOfStack == (capacity-1);}void MyStack::Push(int x){if(this->IsFull()){runtime_error("Full Stack");}else{topOfStack++;*(++myArray) = x;//myArray[++topOfStack] = x;}}void MyStack::Pop(){if(this->IsEmpty()){runtime_error("Empty Stack");}else{topOfStack--;*myArray = NULL;myArray--;}}int MyStack::Top(){if(this->IsEmpty()){runtime_error("Empty Stack");return 0;}else{topOfStack--;return *myArray--;}}
代码经过测试,可用。
- c实现顺序栈
- C实现链式栈
- 栈C语言实现
- C语言实现栈
- 栈的C实现
- c实现顺序栈
- C语言实现栈
- C实现栈
- C语言实现栈
- 栈(c实现)
- C语言实现栈
- C语言实现栈
- 【c++】栈的实现
- C代码实现栈
- C链栈实现
- C链式栈实现
- c语言实现栈
- C语言实现栈
- c#将json转换为dynamic对象 (推荐)
- NHibernate
- 时间格式化最全的类,拷进工程就可使用
- 树莓派上手实战之配置Samba服务器(修正版)(转)
- Java NIO框架Mina、Netty、Grizzly介绍与对比
- C++ 实现栈
- 面向连接例子
- Java允许跨域重载
- android-ocr 光学字符识别技术
- 在Windows server 2008 如何设置只有指定IP地址可以远程登录?
- VTK一路走来
- jQuery弹出窗口插件
- (转)Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析
- mysql采用amoeba集群搭建