链式队列的基本操作

链式队列深度解析:从基础实现到工业级优化

链式队列核心特性

graph TD
    A[链式队列] --> B[内存动态分配]
    A --> C[无容量限制]
    A --> D[高效增删操作]
    B --> E[避免内存浪费]
    C --> F[适合流式数据]
    D --> G[O(1)时间复杂度]

一、现代C++链式队列实现

带头节点模板化实现

#include <memory>
#include <stdexcept>

template <typename T>
class LinkedQueue {
private:
    struct Node {
        T data;
        std::unique_ptr<Node> next;
        Node(T val) : data(val), next(nullptr) {}
    };

    std::unique_ptr<Node> head; // 虚拟头节点
    Node* tail = nullptr;       // 尾指针

public:
    LinkedQueue() : head(std::make_unique<Node>(T())) {
        tail = head.get();
    }

    bool empty() const {
        return head.get() == tail;
    }

    void enqueue(T value) {
        auto newNode = std::make_unique<Node>(value);
        tail->next = std::move(newNode);
        tail = tail->next.get();
    }

    T dequeue() {
        if (empty()) {
            throw std::runtime_error("Dequeue from empty queue");
        }
        
        auto firstNode = std::move(head->next);
        T val = firstNode->data;
        head->next = std::move(firstNode->next);
        
        if (!head->next) {
            tail = head.get();
        }
        return val;
    }
};

关键优化点

  1. 智能指针管理:自动内存释放避免泄漏
  2. 异常安全:空队列出队抛出异常
  3. 模板支持:泛型数据类型存储
  4. 移动语义:高效节点所有权转移

二、带头节点与不带头节点实现对比

1. 结构对比图

带头节点
虚拟头节点
统一操作逻辑
不带头节点
直接数据节点
边界条件复杂

2. 性能对比表

特性带头节点不带头节点
初始化复杂度O(1)O(1)
入队操作统一处理需判空处理
出队操作统一处理需判空处理
内存占用多1个节点更节省内存
代码复杂度

三、工业级扩展功能

1. 迭代器支持

class Iterator {
    Node* current;
public:
    explicit Iterator(Node* node) : current(node) {}
    
    T& operator*() { return current->data; }
    Iterator& operator++() {
        if (current) current = current->next.get();
        return *this;
    }
    bool operator!=(const Iterator& other) { 
        return current != other.current; 
    }
};

Iterator begin() { return Iterator(head->next.get()); }
Iterator end() { return Iterator(nullptr); }

2. 线程安全队列

#include <mutex>

template <typename T>
class ThreadSafeQueue {
    LinkedQueue<T> queue;
    mutable std::mutex mtx;
    std::condition_variable cv;

public:
    void enqueue(T value) {
        std::lock_guard<std::mutex> lock(mtx);
        queue.enqueue(value);
        cv.notify_one();
    }

    T dequeue() {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [this]{ return !queue.empty(); });
        return queue.dequeue();
    }
};

四、复杂度与性能分析

操作时间复杂度空间复杂度缓存友好性
入队(enqueue)O(1)O(1)
出队(dequeue)O(1)O(1)
遍历O(n)O(1)

注:链式结构因指针跳转导致缓存不友好,适合低频大数据量场景


五、典型应用场景

1. 网络数据包缓冲

网卡 队列 处理线程 数据包入队 数据包出队 确认处理完成 网卡 队列 处理线程

2. 生产者-消费者模型

void producer(ThreadSafeQueue<int>& queue) {
    for (int i = 0; ; ++i) {
        queue.enqueue(i);
        std::this_thread::sleep_for(1s);
    }
}

void consumer(ThreadSafeQueue<int>& queue) {
    while (true) {
        int value = queue.dequeue();
        process(value);
    }
}

六、最佳实践指南

1. 实现选择建议

  • 嵌入式系统:不带头节点节省内存
  • 高频交易系统:数组队列更优
  • 通用场景:带头节点实现更稳健

2. 内存管理技巧

// 对象池优化
template <typename T>
class NodePool {
    std::stack<std::unique_ptr<Node>> pool;
public:
    std::unique_ptr<Node> acquire(T val) {
        if (pool.empty()) {
            return std::make_unique<Node>(val);
        }
        auto node = std::move(pool.top());
        pool.pop();
        node->data = val;
        node->next.reset();
        return node;
    }
    
    void release(std::unique_ptr<Node> node) {
        pool.push(std::move(node));
    }
};

七、扩展阅读与测试

单元测试示例

TEST(LinkedQueueTest, BasicOperations) {
    LinkedQueue<int> q;
    ASSERT_TRUE(q.empty());
    
    q.enqueue(10);
    ASSERT_FALSE(q.empty());
    
    ASSERT_EQ(q.dequeue(), 10);
    ASSERT_TRUE(q.empty());
}

TEST(LinkedQueueTest, ThreadSafety) {
    ThreadSafeQueue<int> tsq;
    std::thread producer([&](){
        for (int i = 0; i < 1000; ++i) tsq.enqueue(i);
    });
    
    std::thread consumer([&](){
        for (int i = 0; i < 1000; ++i) tsq.dequeue();
    });
    
    producer.join();
    consumer.join();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

star _chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值