节点被同时链接在list和hashmap中,我是在mfs的readdata.c中看到的,在linux内核代码中经常遇到,单linux内核代码是通过结构中内置list_head实现的,访问时还需要计算结构的首地址。而这里的节点通过m_listnext和m_hashnext用来指向其在list和hashmap中的下一个节点。
图示:
这里写一个简单的演示小程序。
在getnode函数中会创建一个节点,并同时添加到hashmap和list中,代码中并没有实现节点销毁的情况。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAPSIZE 10
typedef struct _node {
struct _node *m_listnext;
struct _node *m_hashnext;
int m_inode;
} node_t;
node_t *g_hashmap[MAPSIZE];
node_t *g_list;
node_t* getnode (int inode) {
node_t *head = g_hashmap[inode%MAPSIZE];
node_t *tmp = 0;
for (; head; head = head->m_hashnext) {
if (head->m_inode == inode) {
return head;
}
}
tmp = (node_t*)malloc (sizeof(node_t));
tmp->m_inode = inode;
tmp->m_hashnext = g_hashmap[inode%MAPSIZE];
g_hashmap[inode%MAPSIZE] = tmp;
tmp->m_listnext = g_list;
g_list = tmp;
return tmp;
}
void display_list () {
node_t* tmp = g_list;
for (; tmp; tmp = tmp->m_listnext) {
printf ("%d ", tmp->m_inode);
}
}
void display_map () {
int i;
for (i = 0; i < MAPSIZE; ++i) {
node_t* tmp = g_hashmap[i];
for (; tmp; tmp = tmp->m_hashnext) {
printf ("%d ", tmp->m_inode);
}
printf ("\n");
}
}
int main () {
int i;
for (i = 0; i < 20; ++i) {
getnode (rand() % 100);
}
display_list ();
printf ("\n\n");
display_map ();
exit (0);
}