双向循环列表(以linux内核链表为模板)

myList.h

//计算member在type中的位置
#if defined(offsetof)
#undef offsetof
#define offsetof(type, member)  (size_t)(&((type*)0)->member)
//根据member的地址获取type的起始地址
#define container_of(ptr, type, member) \
     (type *)((char *)ptr - offsetof(type, member));
#endif

struct list_head{
    struct list_head *next, *prev;
};

static inline void INIT_LIST_HEAD(struct list_head *list)
{
    list->next = list;
    list->prev = list;
}
//插入节点
static inline void __list_add(struct list_head *new_,
struct list_head *prev,
struct list_head *next)
{
    next->prev = new_;
    new_->next = next;
    new_->prev = prev;
    prev->next = new_;
}

static inline void list_add(struct list_head *new_, struct list_head *head)
{
    __list_add(new_, head, head->next);
}

static inline void list_add_tail(struct list_head *new_, struct list_head *head)
{
    __list_add(new_, head->prev, head);
}
//删除节点
static inline void __list_del(struct list_head * prev, struct list_head * next)
{
    next->prev = prev;
    prev->next = next;
}
static inline void list_del(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
    entry->next = NULL;
    entry->prev = NULL;
}

tset程序

#include <iostream>
#include <string>
#include "myList.h"
using namespace std;

struct NodeDong{
    int i;
    char ch;
    list_head dongList;
    NodeDong(int i = 0, char ch = 0) :i(i), ch(ch){}
};
list_head *CreateListByString(string str){
    if (str.empty())
        return NULL;
    int len = str.length();
    list_head *head = new list_head;
    INIT_LIST_HEAD(head);
    int idx = 0;
    while (idx < len){
        NodeDong *node = new NodeDong(idx, str[idx]);
        list_add_tail(&node->dongList, head);
        ++idx;
    }
    return head;
}
void print(list_head *head, int len){
    int i = 0;
    head = head->next;
    while (i < len){
        NodeDong *node = container_of(head, NodeDong, dongList);
        cout << node->i << " -> " << node->ch << endl;
        head = head->next;
        ++i;
    }
}
int main()
{
    string str = "hello dong";
    list_head *head = CreateListByString(str);
    print(head, str.length());
    system("pause");
    return 0;
}

/*
0 -> h
1 -> e
2 -> l
3 -> l
4 -> o
5 ->
6 -> d
7 -> o
8 -> n
9 -> g
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值