首页 > 编程语言 > 详细

C++ 泛型 编写的 数据结构 栈

时间:2017-01-26 10:36:01      阅读:233      评论:0      收藏:0      [点我收藏+]

平时编程里经常需要用到数据结构,比如  栈和队列 等,  为了避免每次用到都需要重新编写的麻烦现将  C++ 编写的 数据结构   栈   记录下来,以备后用。

将 数据结构  栈   用头文件的形式写成,方便调用。

 

#ifndef STACK_CLASS
#define STACK_CLASS

#include<iostream>
#include<cstdlib>
using namespace std;
const int MaxStackSize=50;

//栈类的说明
template <class T>
class Stack
{
private:
    T stacklist[MaxStackSize];
    int top;

public:
    Stack(void);

    void Push(const T &item);
    T Pop(void);
    void ClearStack(void);
    //访问栈顶元素
    T Peek(void) const;

    int StackLength(void) const;
    int StackEmpty(void) const;
    int StackFull(void) const;
};

//默认构造函数
template <class T>
Stack<T>::Stack(void):top(-1)
{}

template <class T>
void Stack<T>::Push(const T &item)
{
    if(top==MaxStackSize-1)
    {
        cerr<<"Stack overflow!"<<endl;
        exit(1);
    }
    top++;
    stacklist[top]=item;
}

template <class T>
T Stack<T>::Pop(void)
{
    T temp;
    if(top==-1)
    {
        cerr<<"Attempt to pop an empty stack"<<endl;
        exit(1);
    }
    temp=stacklist[top];
    top--; 
    return temp; 
}

template <class T>
T Stack<T>::Peek(void) const
{
    if(top==-1)
    {
        cerr<<"Attempt to peek at an empty stack"<<endl;
        exit(1);
    }
    return stacklist[top];
}

template <class T>
int Stack<T>::StackLength(void) const
{
    return top+1;
}

template <class T>
int Stack<T>::StackEmpty(void) const
{
    return top==-1;
}

template <class T>
int Stack<T>::StackFull(void) const
{
    return top==MaxStackSize-1;
}

template <class T>
void Stack<T>::ClearStack(void)
{
    top=-1;
}
#endif

 

具体的调用形式:

技术分享

 

运行结果:

技术分享

 

C++ 泛型 编写的 数据结构 栈

原文:http://www.cnblogs.com/devilmaycry812839668/p/6351280.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!