单链表快速尾部插入

3010阅读 0评论2018-06-06 khls27
分类:LINUX

数据结构:
struact node {
    struct node * next;
    // other members
};

struct node_head {
    struct node *head;
    struct node **tail; // 注意这里的二重指针
};

// init
static struct node_head g_head;
g_head.head = NULL;
g_head.tail = &(g_head.head);

void mlist_add(struct node_head *phead, struct node *node)
{
    node->next = NULL;
    *(phead->tail) = node;
    phead->tail = &node->next;
}

如上面示例代码,该方法在内核中使用较为普遍。原理就是通过维护一个头结点,来分别指向单链表的头部和尾部指针,方便在尾部插入新结点而避免遍历查找尾指针。

另外,单链表通常采用头插法来避免遍历。
上一篇:手把手搭建wordpress环境
下一篇:ubuntu虚拟机安装和配置纪要