---恢复内容开始---

1.栈是一个动态集合。

2.栈实现的是一种后进先出的策略,即被删除的是最近插入的元素。

3.基本用法:

  1. push(): 向栈内压入一个成员;
  2. pop(): 从栈顶弹出一个成员;
  3. empty(): 如果栈为空返回true,否则返回false;
  4. top(): 返回栈顶,但不删除成员;
  5. size(): 返回栈内元素的大小。

4.栈的实现:1.构造模版类

      2.设置数据成员type* //创建一个栈st<

             int top// 记录栈顶

             int maxsize//设置栈的最大长度

 

#include <iostream>

#include <cstdlib>

#define MAXSIZE 100

using namespace std;

 

template <class Type>

class my_stack {

 

    int top;

    Type* st;

    int max;

public:

    my_stack():top(-1),max(MAXSIZE)

    {

        st=new Type[MAXSIZE];

        if (st==NULL) {

            cout << "动态分配内存失败" << endl;

        }

    }

    

    my_stack(int Size):top(-1),max(Size)

    {

        st=new Type[Size];

        if (st==nullptr) {

            cout <<"动态分配内存失败" << endl;

        }

    }

    ~my_stack()

    {

        delete [] st;

    }

    void push(Type a);

    void pop();

    bool empty();

    Type Top();

    int size();

};

 

template<class Type>

void my_stack<Type>::push(Type a)

{

    if (top+1<max) {

        st[++top]=a;

    }

    else{

        cout << "栈已经满了";

        exit(1);

    }

}

 

template<class Type>

void my_stack<Type>::pop()

{

    if (top>=0) {

        top--;

    }

    else

    {

        cout << "栈空" << endl;

        exit(1);

    }

}

 

 

template <class Type>

bool my_stack<Type>::empty()

{

    if (top!=-1)

    {

        return true;

    }

    else

    {

        return false;

    }

}

 

 

template <class Type>

Type my_stack<Type>::Top()

{

    if (top>=0) {

        return st[top];

    }

    else

    {

        cout << "空表" << endl;

        exit(1);

    }

}

 

template <class Type>

int my_stack<Type>::size()

{

    return top+1;

}

 

posted @ 2018-05-08 22:10  QianweiZ  阅读(141)  评论(0编辑  收藏  举报