【C程序】用宏实现链表的基本接口

LIST(type, name) // 声明一个表结构体

LINK(type, link) // 声明一个链表结构体

LIST_INIT(list) // 初始化一个表

LINK_INIT(link) // 初始化一个链表

LIST_HEAD(list.head) // 表头指针

LIST_TAIL(list.tail) // 表尾指针

LIST_CNT(list.cnt) // 节点数

LIST_REMOVE(list, node, link) // 从链表中删除一个节点数据

LIST_ADD(list, node, link) // 往链表尾部中添加一个节点数据

LIST_FIND(list, iter, link, test) // 以iter指针为遍历指针,找到想要的test节点数据

#define LIST(type, name) \
  struct { \
    type *head; \
    type *tail; \
    unsigned int count; \
  } name

#define LINK(type, link) \
  struct { \
    type *prev; \
    type *next; \
  } link

#define LIST_INIT(list) do {  \
  (list).head = (list).tail = NULL; \
  (list).count = 0; \
} while(0)

#define LINK_INIT(link) (link).next = (link).prev = NULL
#define LIST_HEAD(list) (list.head)
#define LIST_TAIL(list) (list.tail)
#define LIST_CNT(list) (list.count)

#define LIST_REMOVE(list, node, link) \
  do { \
    if((node)->link.prev) \
      (node)->link.prev->link.next = (node)->link.next; \
    else /* node at the front of the list */ \
      list.head = (node)->link.next; \
    if((node)->link.next) \
      (node)->link.next->link.prev = (node)->link.prev; \
    else /* node at the end of the list */ \
      list.tail = (node)->link.prev; \
    list.count--; \
  } while(0)

#define LIST_ADD(list, node, link) \
  do { \
    if(!list.tail) \
    { \
      /* first node on the list */ \
      list.tail = list.head = node; \
    } \
    else \
    { \
      (node)->link.prev = list.tail; \
      list.tail->link.next = node; \
      list.tail = node; \
    } \
    list.count++; \
  } while(0)

#define LIST_FIND(list, iter, link, test) do {  \
  iter = (list).head; \
  while(iter) { \
    if(test) {  \
      break;  \
    } \
    iter = (iter)->link.next;  \
  } \
} while(0)

猜你喜欢

转载自blog.csdn.net/sinat_36184075/article/details/80398256