队列(c++实现)

  队列的特点是先进先出,跟栈的c++实现类似,队列的c++实现同样有两种方式:
这里写图片描述
  Queue是一个接口类,封装了队列相关的所有操作:

//Queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__

#include <exception>

template<typename T>
class Queue
{
public:
    virtual void add(const T& e) = 0;   //向队列增加元素
    virtual void remove() = 0;          //删除队列(头)元素
    virtual T front() const = 0;        //获取队列(头)元素
    virtual void clear() = 0;           //清空队列
    virtual int length() const = 0;     //获取队列长度
};

#endif /* __QUEUE_H__ */

  队列数据结构其实就是前面讲的环形缓冲区,核心是两个循环计数的指针分别表示读/写位置
  队列空间是静态分配的数组:

//StaticQueue.h
#ifndef __STATICQUEUE_H__
#define __STATICQUEUE_H__

#include "Queue.h"

template <typename T, int N>
class StaticQueue : public Queue<T>
{
protected:
    T m_space[N];
    int m_write;
    int m_read;
    int m_length;

public:
    StaticQueue() : m_write(0), m_read(0), m_length(0)
    {
    }

    int capacity() const
    {
        return N;
    }

    void add(const T& e)
    {
        if (m_length < N)
        {
            m_space[m_write] = e;
            m_write = (m_write + 1) % N;
            ++m_length;
        }
        else
            throw(std::runtime_error("No space in current queue"));
    }

    void remove()
    {
        if (m_length > 0)
        {
            m_read = (m_read + 1) % N;
            --m_length;
        }
        else
            throw(std::runtime_error("No element in current queue"));
    }

    T front() const
    {
        if (m_length > 0)
            return m_space[m_read];
        else
            throw(std::runtime_error("No element in current queue"));
    }

    void clear()
    {
        m_write = 0;
        m_read = 0;
        m_length = 0;
    }

    int length() const
    {
        return m_length;
    }
};

#endif /* __STATICQUEUE_H__ */

  测试:

//main.cpp
int main(void)
{
    StaticQueue<int, 6> queue;

    for (int i = 0; i < 6; ++i)
    {
        queue.add(i);
    }

    while (queue.length() > 0)
    {
        std::cout << queue.front() << std::endl;
        queue.remove();
    }

    getchar();
    return 0;
}

  用链表实现队列空间,这里采用Linux内核链表来实现:

//LinkQueue.h
#ifndef __LINKQUEUE_H__
#define __LINKQUEUE_H__

#include "linux_list.h"
#include "Queue.h"

template<typename T>
class LinkQueue : public Queue<T>
{
protected:
    struct Node_t
    {
        list_head head;
        T value;
    };

    list_head m_head;
    int m_length;

public:
    LinkQueue()
    {
        m_length = 0;
        INIT_LIST_HEAD(&m_head);
    }

    void add(const T& e)
    {
        Node_t *node = new Node_t();
        if (node)
        {
            node->value = e;
            list_add_tail(&node->head, &m_head);
            ++m_length;
        }
        else
            throw(std::runtime_error("No memory in create queue"));
    }

    void remove()
    {
        if (m_length > 0)
        {
            list_head* toDel = m_head.next;
            list_del(toDel);
            --m_length;
            delete list_entry(toDel, Node_t, head);
        }
        else
            throw(std::runtime_error("No element in current queue"));
    }

    T front() const
    {
        if (m_length > 0)
        {
            return list_entry(m_head.next, Node_t, head)->value;
        }
        else
            throw(std::runtime_error("No element in current queue"));
    }

    void clear()
    {
        while (m_length > 0)
            remove();
    }

    int length() const
    {
        return m_length;
    }

    ~LinkQueue()
    {
        clear();
    }

};

#endif /* __LINKQUEUE_H__ */
<think>好的,用户想了解如何用C++实现队列数据结构,需要示例代码或教程。首先,我需要回忆队列的基本概念,队列是FIFO结构,支持入队和出队操作。常见的实现方式有数组和链表。 接下来,查看用户提供的引用内容。引用[1]和[3]提到了队列C++实现,特别是引用[3]中有一个顺序队列的示例代码。不过,用户提供的引用中的代码可能存在格式问题,比如使用了&这样的HTML实体,需要转换为&符号。此外,引用中的代码可能使用了C风格的函数指针,而C++中更常用类来封装数据结构。 用户需要的是清晰的示例代码和教程步骤。因此,我应该分步骤讲解,首先用数组实现循环队列,然后用链表实现。循环队列需要注意队满和队空的判断条件,通常通过预留一个位置或者使用计数器来解决。链表实现则更灵活,无需担心容量问题。 还需要注意代码的现代C++风格,比如使用类模板、智能指针等,但考虑到用户可能更倾向于基础实现,先提供结构化的类实现,再考虑模板化。同时,要确保代码的正确性,比如指针操作、内存管理等。 最后,生成相关问题,帮助用户深入理解队列的应用和扩展,比如性能优化、线程安全等。需要确保问题与队列相关,并且能够引导用户进一步学习。</think>### C++队列实现详解 队列是先进先出(FIFO)的线性数据结构,包含入队(enqueue)和出队(dequeue)两个基本操作[^1]。以下是两种常见的实现方式: #### 一、数组实现(循环队列) ```cpp #include <iostream> using namespace std; const int MAX_SIZE = 5; class ArrayQueue { private: int data[MAX_SIZE]; int front; int rear; public: ArrayQueue() : front(0), rear(0) {} bool enqueue(int value) { if ((rear + 1) % MAX_SIZE == front) { // 队满判断 cout << "队列已满!" << endl; return false; } data[rear] = value; rear = (rear + 1) % MAX_SIZE; return true; } bool dequeue() { if (front == rear) { // 队空判断 cout << "队列为空!" << endl; return false; } front = (front + 1) % MAX_SIZE; return true; } int getFront() { if (front == rear) return -1; return data[front]; } }; // 使用示例 int main() { ArrayQueue q; q.enqueue(10); q.enqueue(20); cout << "队首元素:" << q.getFront() << endl; q.dequeue(); cout << "新队首:" << q.getFront() << endl; return 0; } ``` 关键点说明: 1. 使用模运算实现循环队列,解决假溢出问题 2. 队满条件:$(rear+1)\%MAX\_SIZE == front$ 3. 队空条件:$front == rear$[^3] #### 二、链表实现 ```cpp #include <iostream> using namespace std; struct Node { int data; Node* next; Node(int val) : data(val), next(nullptr) {} }; class LinkedListQueue { private: Node* front; Node* rear; public: LinkedListQueue() : front(nullptr), rear(nullptr) {} void enqueue(int value) { Node* newNode = new Node(value); if (rear == nullptr) { front = rear = newNode; return; } rear->next = newNode; rear = newNode; } void dequeue() { if (front == nullptr) return; Node* temp = front; front = front->next; if (front == nullptr) rear = nullptr; delete temp; } int getFront() { return front ? front->data : -1; } }; ``` ### 实现步骤解析 1. **初始化**:设置队首和队尾指针 2. **入队操作**: - 数组实现:检查队列是否已满,更新rear指针 - 链表实现:创建新节点,更新尾部指针 3. **出队操作**: - 数组实现:移动front指针 - 链表实现:释放头节点内存,更新front指针 4. **边界处理**: - 数组实现需处理循环逻辑 - 链表实现需处理空队列情况 ### 性能对比 | 实现方式 | 时间复杂度 | 空间利用率 | 适用场景 | |----------|------------|------------|----------| | 数组 | O(1) | 固定容量 | 已知最大容量 | | 链表 | O(1) | 动态扩展 | 频繁插入删除 |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值