双向链表的实现

链表的结构

image.png

链表的操作

image.png

创建链表

  1. list *listCreate(void)
  2. {
  3. struct list *list;
  4. if ((list = zmalloc(sizeof(*list))) == NULL)
  5. return NULL;
  6. list->head = list->tail = NULL;
  7. list->len = 0;
  8. list->dup = NULL;
  9. list->free = NULL;
  10. list->match = NULL;
  11. return list;
  12. }

插入链表头部或尾部

  1. list *listAddNodeTail(list *list, void *value)
  2. {
  3. listNode *node;
  4. if ((node = zmalloc(sizeof(*node))) == NULL)
  5. return NULL;
  6. node->value = value;
  7. if (list->len == 0) {
  8. list->head = list->tail = node;
  9. node->prev = node->next = NULL;
  10. } else {
  11. node->prev = list->tail;
  12. node->next = NULL;
  13. list->tail->next = node;
  14. list->tail = node;
  15. }
  16. list->len++;
  17. return list;
  18. }

插入到某个节点前后

  1. list *listInsertNode(list *list, listNode *old_node, void *value, int after) {
  2. listNode *node;
  3. if ((node = zmalloc(sizeof(*node))) == NULL)
  4. return NULL;
  5. node->value = value;
  6. if (after) {
  7. node->prev = old_node;
  8. node->next = old_node->next;
  9. if (list->tail == old_node) {
  10. list->tail = node;
  11. }
  12. } else {
  13. node->next = old_node;
  14. node->prev = old_node->prev;
  15. if (list->head == old_node) {
  16. list->head = node;
  17. }
  18. }
  19. if (node->prev != NULL) {
  20. node->prev->next = node;
  21. }
  22. if (node->next != NULL) {
  23. node->next->prev = node;
  24. }
  25. list->len++;
  26. return list;
  27. }