博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Customized version of Stack C++
阅读量:4709 次
发布时间:2019-06-10

本文共 2277 字,大约阅读时间需要 7 分钟。

Stack1.h
#ifndef  stack_#define stack_#include "stdafx.h"//#include 
//using namespace std;//exceptionclass OutOfBounds{public: OutOfBounds(){}};//change array's sizetemplate
void Changesize1D(T * &arr,const int& size,const int& ToSize){ T* tmp = new T[size]; tmp = arr; arr = new T[ToSize]; for(int i=0; i< size; ++i){ arr[i] = tmp[i]; } delete[] tmp;}template
class Stack{ //friend ostream& operator<<(ostream&, const Stack
&);public: Stack(); ~Stack(){delete []stack;}; T Top() const; void Pop(); void Push(const T& x); int Size() const; bool Empty();private: int top; int Maxtop; T* stack;};template
Stack
::Stack() { stack = new T[1]; top = -1; Maxtop = 0;}template
T Stack
::Top() const{ if(top == -1){ throw OutOfBounds(); }else{ return stack[top]; }}template
void Stack
::Pop(){ --top; //change array capacity when the list size drops to //one-fourth of the array capacity if((top + 1 <= (Maxtop + 1)/4) && Maxtop >0){ Maxtop = (Maxtop - 1)/2; Changesize1D(stack,top + 1, Maxtop + 1); }}template
void Stack
::Push(const T& x){ //if there is not enough space to accommodate the new element, //double the array capacity if(top == Maxtop){ Maxtop = Maxtop * 2 + 1; Changesize1D(stack,top + 1,Maxtop + 1); } stack[++top] = x;}template
int Stack
::Size() const{ return top + 1;};template
bool Stack
::Empty(){ return top == -1;}/*template
ostream& operator<<(ostream& out, const Stack
& s){ out << "The stack has " << s.Size() << " element(s)" << endl; return out;}*/#endif
Test it
// Stack.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "Stack1.h"#include 
using namespace std;int main(int argc, char* argv[]){ Stack
t; try { t.Top(); } catch (OutOfBounds e) { cout << "no element" << endl; } t.Push(1); cout << "after push 1, the top:" << t.Top() << endl; cout << "after push 1, is empty?:" <
<< endl; t.Pop(); cout << "after pop, is empty? " <
<< endl; for(int i=0; i<10; ++i){ t.Push(i); } while(!t.Empty()){ cout << t.Top() << endl; t.Pop(); } return 0;}

转载于:https://www.cnblogs.com/easycpp/p/3403525.html

你可能感兴趣的文章
通过Html5 Canvas画柱状图
查看>>
青蛙跳台阶(Fibonacci数列)
查看>>
洛谷P3834 [模板]可持久化线段树1(主席树) [主席树]
查看>>
Codeforces Round #316 (Div. 2)C. Replacement(模拟)
查看>>
Python入门学习笔记17(sqlalchemyd的使用)
查看>>
.NET CORE TOKEN 权限验证
查看>>
.Net Core 中间件之主机地址过滤(HostFiltering)源码解析
查看>>
cordova百度地图定位Android版插件
查看>>
WPF最大化避免覆盖任务栏
查看>>
解决引用 System.Windows.Interactivity程序集生成多国语言文件夹fr、es、ja等问题
查看>>
UWP入门(十一)--使用选取器打开文件和文件夹
查看>>
Win8 Metro(C#)数字图像处理--2.60部分彩色保留算法
查看>>
Lucene.Net 2.3.1开发介绍 —— 一、接触Lucene.Net
查看>>
数据库开发篇(一)——转换日期类型
查看>>
第三篇——第二部分——第一文 SQL Server镜像简介
查看>>
CSS实现背景透明,文字不透明(兼容各浏览器)
查看>>
SQL Server中的Merge关键字
查看>>
算法起步之选择算法
查看>>
WiX Toolset
查看>>
NSArray和NSMutableArray的常用方法 (转)
查看>>