C++ :将顺序栈、循环队列定义成模板类

1.思维导图: 

2. 将顺序栈、循环队列定义成模板类

顺序栈Mystack

#include 

using namespace std;

template 
class Mystack
{
private:
    T *ptr;
    int size;
    int top;

public:
    Mystack():ptr(new T[10]),top(-1){};
    Mystack(int s):ptr(new T[size]),size(s),top(-1){};
    ~Mystack()
    {
        delete []ptr;
    }

    Mystack&operator = (const Mystack&other)
    {
        if(this == &other)
        {
            return *this;
        }

        delete []ptr;

        return strncat(this->ptr,&other.ptr,size);
    }

    bool empty()
    {
        return top == -1;
    }

    bool full()
    {
        return top== size-1;
    }

    int getsize()
    {
        return top+1;
    }

    int push(T pos)
    {
        if(top == size -1)
        {
            return  -1;
        }
        ptr[++top]= pos;
        return 0;
    }

    void pop()
    {
        if(top ==-1)
        {
            return;
        }
        top--;
    }

    T& gettop()
    {
        return ptr[top];
    }

    void output()
    {
     if(top == -1)
         return;
     for(int i=0;i<=top;i++)
     {
         cout<

循环队列

 

#include 

using namespace std;
template 
class loopqueue
{
private:
    T *ptr;  //队列的首地址
    int size;  //队列大小
    int front;  //队头
    int rear;   //队尾

public:
    loopqueue(){};
    loopqueue(int s):ptr(new T[size]),size(s),front(0),rear(0){};
    ~loopqueue()
    {
        delete []ptr;
    };

    loopqueue &operator = (const loopqueue &other)
    {
        if(this == &other)
        {
            return *this;
        }
        delete []ptr;

        return strncat(this->ptr,&other.ptr,size);
    }

    bool emtpy()
    {
        return front == rear;
    }

    bool full()
    {
        return front = (rear+1)%size;
    }

    int size
    {
        return maxsize = front
    }

    int push(T data)
    {
        if(full())
        {
            return -1;
        }
        rear = (rear +1)%size;
        return 0;
    }

    int pop()
    {
        if(empty())
        {
            return -1;
        }
        front = (front +1)%size;
        return 0;
    }

    int getsize()
    {
        return (size - front+rear)%size;
    }

    void output()
    {
        if(empty())
        {
            return -1;
        }
        for(int i=front;i!=rear;i=(i+1)%size)
        {
            cout<

你可能感兴趣的:(c++,算法,开发语言)