数据结构(4) 顺序栈 c++ 模板实现
来源:互联网 发布:淘宝子账号怎么设置 编辑:程序博客网 时间:2024/06/17 00:02
顺序栈
栈的顺序存储结构简称为顺序栈,它是运算受限的顺序表。实现同样是数组。
//SeqStack.htemplate <typename Type> class SeqStack{private:int m_TopofStack;Type *m_pbase;int m_nMaxsize;public:SeqStack(int size=10):m_TopofStack(-1),m_nMaxsize(size){m_pbase=new(nothrow) Type[size];//new的nothrow版本,失败则返回一个空指针if (m_pbase==NULL){cout<<"error!"<<endl;exit(-1);}};//将m_TopofStack=-1是为了适应数组下标的命名习惯,为0时就是有一个元素~SeqStack(){ delete []m_pbase;}public:void ClearStack();bool Push(const Type item);//压栈Type Pop();//出栈Type Peek() const;//获得头元素void Print();//void ReNew(int plussize=10);int Length();bool IsEmpty(){return m_TopofStack==-1;}bool IsFull(){return m_TopofStack==m_nMaxsize-1;}//因为m_TopofStack比实际的元素数量小1};template <typename Type> void SeqStack<Type>::ClearStack(){//while(m_TopofStack>=0);//m_pbase[m_TopofStack--]=NULL;m_TopofStack=-1;}template <typename Type> int SeqStack<Type>::Length(){return m_TopofStack+1;}template <typename Type> bool SeqStack<Type>::Push(const Type item){if(SeqStack<Type>::IsFull()){cout<<"The stack is full!"<<endl;return false;}m_pbase[++m_TopofStack]=item;return true;}template <typename Type> Type SeqStack<Type>::Pop(){if(SeqStack<Type>::IsEmpty()){cout<<"Stack is empty!"<<endl;return NULL;} return m_pbase[m_TopofStack--];}template <typename Type> Type SeqStack<Type>::Peek() const{if(SeqStack<Type>::IsEmpty()){cout<<"Stack is empty!"<<endl;return NULL;}return m_pbase[m_TopofStack];}template <typename Type> void SeqStack<Type>::Print(){for(int i=0;i<=m_TopofStack;i++)cout<<m_pbase[i]<<endl;}
测试代码:
//SeqStack.cpp#include "stdafx.h"#include "SeqStack.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){SeqStack<int> stack;for(int i=0;i<10;i++)stack.Push(i);stack.Print();stack.Push(88);cout<<stack.Pop()<<endl;stack.Print();stack.ClearStack();stack.Print();stack.Pop();stack.Print();return 0;}
- 数据结构(4) 顺序栈 c++ 模板实现
- [数据结构] 顺序表的实现(c++/类模板)
- 数据结构学习系列五-顺序栈(c++实现且应用模板)
- 数据结构(C++)-用顺序结构实现的栈模板类
- 数据结构--顺序栈实现(c语言)
- 数据结构(C实现)------- 顺序栈
- 【数据结构】顺序栈的实现(c++)
- 数据结构之顺序栈(数组)C++(模板)
- 数据结构:栈的顺序结构及实现(C++)
- 数据结构--顺序栈的实现(C语言)
- C语言实现数据结构中的顺序栈
- 数据结构的C实现_顺序栈
- 数据结构---栈顺序表c实现
- 数据结构C语言实现之顺序栈
- <数据结构>顺序栈的C语言实现
- 数据结构-顺序栈-C语言实现
- 数据结构(C实现)------- 顺序表
- 【数据结构】实现顺序表(c++)
- 修改VirtualBox的BIOS 体验OEM
- iframe的src赋值问题(服务器端)
- Ajax学习笔记
- linux的system () 函数详解
- python模块:win32com用法详解
- 数据结构(4) 顺序栈 c++ 模板实现
- hdu 2063 过山车 ( 二分图最大匹配水过 .)
- NEFU709(第K个圆的半径)
- kdump
- 构建RESTful风格的WCF服务
- sql 入门经典总结
- 内核编译出现错误
- Learning Hadoop
- CodeForces 154B——Colliders——筛选素数,模拟标记