面向对象的简易栈,队列实现

//顺序栈
class Stack
{
private:
    int size;
    int top;
    char *st;
public:
    Stack(int);
    bool push(char e);
    bool pop(char &e);
};

Stack::Stack(int msize)
{
    size = msize;
    top = -1;
    st = new char[size];
}

bool Stack::push(char e)
{
    if (top == size - 1)
    {
        cout << "栈满" << endl;
        return false;
    }    
    else 
    {
        st[++top] = e;
        return true;
    }
}

bool Stack::pop(char &c)
{
    if (top == -1)
    {
        cout << "栈空" << endl;
        return false;
    }
    else
    {
        c = st[top--];
        return true;
    }

}


//链式栈
class LNode
{
public:
    char data;
    LNode *next;

};
class LStack
{
public:
    LStack();
    bool push(char e);
    bool pop(char &e);
private:
    LNode *top;
};

LStack::LStack()
{
    top = NULL;
}
bool LStack::push(char e)
{
    LNode *ptr = new LNode;
    ptr->data = e;
    ptr->next = top;
    top = ptr;
    return true;
}

bool LStack::pop(char &e)
{
    if (top == NULL)
    {
        cout << "栈空" << endl;
        return false;
    }
    else
    {
        LNode *ptr = top;
        e = top->data;
        top = top->next;
        delete ptr;
        return true;
    }
    
}

//顺序队
class Queue
{
private:
    int MaxSize;
    int front;
    int rear;
    char *qu;
public:
    Queue(int size);
    bool enQueue(char e);
    bool deQueue(char &e);
};
Queue::Queue(int size)
{
    MaxSize = size;
    rear = front = 0;
    qu = new char[MaxSize];
}
bool Queue::enQueue(char e)
{
    if ((rear + 1) % MaxSize == front)
    {
        cout << "队满" << endl;
        return false;
    }
    rear = (rear + 1) % MaxSize;
    qu[rear] = e;
    return true;
}
bool Queue::deQueue(char &e)
{
    if (rear == front)
    {
        cout << "队空" << endl;
        return false;
    }
    front = (front + 1) % MaxSize;
    e = qu[front];
    return true;
}

//链队
class LQueue
{
private:
    LNode *front;
    LNode *rear;
public:
    LQueue();
    bool enQueue(char e);
    bool deQueue(char &e);
};
LQueue::LQueue()
{
    front = rear = NULL;
}
bool LQueue::enQueue(char e)
{
    
    LNode *p = new LNode;
    p->data = e;
    p->next = NULL;
    if (rear == NULL)
        
        rear = front = p;

    else
    {
        rear->next = p;
        rear = p;
    }
    return true;
}
bool LQueue::deQueue(char &e)
{
    LNode *p;
    if (rear == NULL)
    {
        cout << "队空" << endl;
        return false;
    }
    else
        p = front;
    if (front == rear)
    {
        front = rear = NULL;
    }
    else
        front = front->next;
    e = p->data;
    delete p;
    return true;
}

 

转载于:https://www.cnblogs.com/joy-1120/p/10593939.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值