c++ 实现自定义栈(用数组实现)也叫顺序栈

**********************************.h文件**************************

#include "myutill.h"
#ifndef SQUENTIALSTACK_MYSTACK_H
#define SQUENTIALSTACK_MYSTACK_H

template <class T>
class Mystack
{
public:
    Mystack(int capacity);
    ~Mystack();
    bool isempty();
    T& Top();
    void push(const T& item);
    void pop();
private:
    T* stack;
    int top;
    int capacity;
};

template <class T>
Mystack<T>::Mystack(int capacity) {
    this->capacity=capacity;
    if(capacity<1) throw "stack capacity must be >0";
    stack=new T[capacity];
    top=-1;
}

template <class T>
Mystack<T>::~Mystack() {
    delete[] stack;
}
template <class T>
void Mystack<T>::push(const T &item) {

    if(top==capacity-1)
    {
        Changesize(stack,capacity,2*capacity);
        capacity*=2;
    }
    stack[++top]=item;
}
template <class T>
inline bool Mystack<T>::isempty() {
    return top==-1;
}
template <class T>
inline T& Mystack<T>::Top() {
    if (isempty()) throw "stack is empty";
    else
    {
        return stack[top];
    }
}
template <class T>
void Mystack<T>::pop() {
    if(isempty())
    {
        throw "stack is empty. cannot delete";
    }
    top--;//简单的删除,堆栈保存的是基础的数据类型

    stack[top--].~T();//****************当栈保存的是对象的时候,删除时并调用对象的析构函数***********88
}



#endif //SQUENTIALSTACK_MYSTACK_H

 

****************************mutill.h***************************

#include <iostream>
#ifndef SQUENTIALSTACK_MYUTILL_H
#define SQUENTIALSTACK_MYUTILL_H
using namespace std;
template <class T>
void Changesize(T* &a,int oldsize,int newsize);

template <class T>
void Changesize(T* &a,int oldsize,int newsize)
{
    if(newsize<0) throw "newsize must be >=0";
    T* temp=new T[newsize];
    int number=min(oldsize,newsize);
    copy(a,a+number,temp);
    delete[] a;
}

#endif //SQUENTIALSTACK_MYUTILL_H

 

*********************************.cpp实现****************************

#include <iostream>
#include "myutill.h"
#include "mystack.h"


int main() {

    Mystack<int> st(5);
    st.push(9);
    int a=st.Top();
    cout<<"a= "<<a<<endl;

    return 0;
}
上一篇:栈————用队列实现栈


下一篇:自定义堆和栈