实现链式队列

队列(queue)在计算机科学中,是一种先进先出的线性表。它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作。

队列可以采用顺序存储方式来实现(称为顺序队列),或者采用链式存储方式来实现(称为链式队列)。

实现链式队列需要注意:
(1)采用动态链表作为存储结构;
(2)不需要预分配空间,比顺序队列更灵活;
(3)没有链式队列满状态这种说法,因为没有定义最大内存空间;
(4)与顺序队列相似,有空出一个结点没有使用;
(5)当删除最后一个结点时,需要做调整:rear = front; 避免rear指针指向一个已经删除的结点;

以下为实现代码,在vs2010上测试通过:

#include <iostream>
using namespace std;

struct node
{
    int data;
    node* next;
};

class queue
{
public:
    queue();
    ~queue();
    bool empty();
    //bool full();//链式没有满的情况
    bool getTopElement(int &x);
    bool push(int x);
    bool pop();
    int size();

private:
    int count;
    node* front, *rear;
};

int _tmain(int argc, _TCHAR* argv[])
{
    queue que;
    for(int i = 0; i < 5; i++)
        que.push(i);

    int x;
    while(!que.empty())//验证是否满足“先进后出原则”
    {
        que.getTopElement(x);
        que.pop();
    }

    return 0;
}

queue::queue()
{
    count = 0;
    front = new node;
    rear = front;
    front->next = NULL;//空出一个结点没有使用
}

bool queue::empty()
{
    if (count == 0)
        return true;
    else
        return false;
}

bool queue::getTopElement(int &x)//访问队列头元素
{
    if(empty())
        return UNDERFLOW;
    else
    {
        x = front->next->data;//中间隔了一个空结点
        return true;
    }
}

//队列在尾部添加元素,堆栈在顶部添加元素
bool queue::push(int x)//弹出队列头元素
{
    node* s = new node;
    s->data = x;
    s->next = NULL;
    rear->next = s;
    rear = s;
    count ++;
    return true;
}

bool queue::pop()//弹出队列头元素
{
    if(empty())
        return OVERFLOW;
    else
    {
        node* u = front->next;
        front->next = u->next;
        delete u;
        count--;
        if(front->next == NULL)//当删除最后一个元素时,需要调整
            rear = front;//避免rear指针指向一个已经删除的结点
        return true;
    }
}

int queue::size()
{
    return count;
}

queue::~queue()
{
    while(!empty())
        pop();
    delete front;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值