一种双向链表设计方法(C++)

leveldb源码实现的双向链表。
设计思想:
<1>链表由表头和表元素构成
<2>表头是一个特殊的表元素
<3>元素从表尾插入
链表实现:

class SnapshotImpl;
class SnapshotList 
{
public:
    SnapshotList() 
    {
        list_.prev_ = &list_;
        list_.next_ = &list_;
    }

    bool empty() const 
    { 
        return list_.next_ == &list_; 
    }
    SnapshotImpl* oldest() const 
    { 
        assert(!empty());
        return list_.next_; 
    }
    SnapshotImpl* newest() const 
    { 
        assert(!empty()); 
        return list_.prev_; 
    }

    const SnapshotImpl* New(int seq) 
    {
        SnapshotImpl* s = new SnapshotImpl;
        s->number_ = seq;
        s->list_ = this;
        s->next_ = &list_;
        s->prev_ = list_.prev_;
        s->prev_->next_ = s;
        s->next_->prev_ = s;
        return s;
    }

    void Delete(const SnapshotImpl* s) {
        assert(s->list_ == this);
        s->prev_->next_ = s->next_;
        s->next_->prev_ = s->prev_;
        delete s;
    }

private:
    // Dummy head of doubly-linked list of snapshots
    SnapshotImpl list_;
};

表元素:

// Abstract handle to particular state of a DB.
// A Snapshot is an immutable object and can therefore be safely
// accessed from multiple threads without any external synchronization.
class Snapshot 
{
protected:
    virtual ~Snapshot();
};
Snapshot::~Snapshot() 
{
}

class SnapshotList;
// Snapshots are kept in a doubly-linked list in the DB.
// Each SnapshotImpl corresponds to a particular sequence number.
class SnapshotImpl : public Snapshot 
{
public:
    int number_;  // const after creation

private:
    friend class SnapshotList;

    // SnapshotImpl is kept in a doubly-linked circular list
    SnapshotImpl* prev_;
    SnapshotImpl* next_;

    SnapshotList* list_;                 // just for sanity checks
};

测试程序:

    SnapshotList snapShotListHeader;
    for(int nCount = 0; nCount < 100; ++nCount)
    {
        snapShotListHeader.New(nCount);
    }

    ::std::cout << snapShotListHeader.oldest()->number_ << ::std::endl;
    ::std::cout << snapShotListHeader.newest()->number_ << ::std::endl;

    getchar();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值