7.22 作业

1 思维导图

7.22 作业_第1张图片

 2. 写一个stack模板

#include 
using namespace std;

template 
class MyStack
{
    T *ptr;
    unsigned long top = -1;
    unsigned long size;
public:
    MyStack():size(10)
    {
        ptr = new T[size];
    };
    MyStack(unsigned long s):size(s)
    {
        ptr = new T[size];
    }
    MyStack(const MyStack& s):size(s.size),top(s.top)
    {
        ptr = new T[size];
        for(int i=0;i<=s.top;i++)
        {
            ptr[i] = s.ptr[i];
        }
    }
    ~MyStack()
    {
        delete [] ptr;
    }
    MyStack& operator = (const MyStack& s)
    {
        if(s!=*this)
        {
            size = s.size;
            top = s.top;
            delete [] ptr;
            ptr = new T[size];
            for(int i=0;i<=s.top;i++)
            {
                ptr[i] = s.ptr[i];
            }
        }
    }
    T& gettop()
    {
        if(top != -1)
        {
            return ptr[top];
        }
    }
    bool isempty()
    {
        return top<0;
    }
    unsigned long getsize()
    {
        return top+1;
    }
    bool isfull()
    {
        return size == top+1;
    }
    void push(T t)
    {
        ptr[++top] = t;
    }
    void pop()
    {
        top--;
    }
};

3.queue模板

#include 
using namespace std;

template
class myqueue
{
    T *ptr;
    int front = 0;
    int back = 0;
    int size = 10;
public:
    myqueue():ptr(new T[size]){}
    myqueue(int s):size(s),ptr(new T[s]){}
    myqueue(const myqueue& q):ptr(new T[q.size]),
        front(q.front),back(q.back),size(q.size)
    {
        for(int i = front;i!=back;i=(i+1)%size)
        {
            ptr[i] = q.ptr[i];
        }
    }
    ~myqueue()
    {
        delete []ptr;
    }
    const T& getfront()
    {
        if(!isempty())
        {
            return ptr[front];
        }
    }
    const T& getback()
    {
        if(!isempty())
        {
            return ptr[(back+size-1)%size];
        }
    }
    bool isempty()
    {
        return front==back;
    }
    bool isfull()
    {
        return front == (back+1)%size;
    }
    int getlen()
    {
        return (back-front+size)%size;
    }
    void push(T t)
    {
        if(isfull()) return;
        ptr[back++] = t;
        back %= size;
    }
    void pop()
    {
        if(isempty()) return;
        front = (front+1)%size;
    }
};

你可能感兴趣的:(c++)