list.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // 双向链表结构
  2. #ifndef __LIB_KERNEL_LIST_H
  3. #define __LIB_KERNEL_LIST_H
  4. #include "../stdint.h"
  5. // 获取结构体中成员的偏移量, 并将其转换为 void* 类型
  6. #define offset(struct_type, member) (uintptr_t)(&((struct_type *)0)->member)
  7. #define elem2entry(struct_type, struct_member_name, elem_ptr) \
  8. (struct_type *)((uintptr_t)elem_ptr - offset(struct_type, struct_member_name))
  9. // 链表节点, 节点中不需要数据成员, 只要求前驱和后继指针
  10. struct list_elem
  11. {
  12. struct list_elem *prev; // 前驱节点
  13. struct list_elem *next; // 后继节点
  14. };
  15. // 链表结构, 用来实现队列
  16. struct list
  17. {
  18. struct list_elem head; // 链表头, 链表起始元素, 不是第一个元素
  19. struct list_elem tail; // 链表尾, 链表终止元素, 不是最后一个元素
  20. };
  21. // 自定义函数类型 trav_func, 用于在list_traversal中做回调函数
  22. typedef bool trav_func(struct list_elem *, int arg);
  23. /****************************** function声明 ******************************/
  24. // 初始化双向链表list
  25. void list_init(struct list *);
  26. // 将链表元素elem 插入在元素before之前
  27. void list_insert_before(struct list_elem *before, struct list_elem *elem);
  28. // 将元素elem添加到链表plist队首,类似栈push操作
  29. void list_push(struct list *plist, struct list_elem *elem);
  30. void list_iterate(struct list *plist);
  31. void list_append(struct list *plist, struct list_elem *elem);
  32. // 从链表中删除元素pelem
  33. void list_remove(struct list_elem *pelem);
  34. // 将链表第一个元素弹出并返回
  35. struct list_elem *list_pop(struct list *plist);
  36. // 判断链表是否为空,空返回true,否则返回false
  37. bool list_empty(struct list *plist);
  38. // 返回链表长度
  39. uint32_t list_len(struct list *plist);
  40. // 把列表plist中的每个元素elem和arg传给func,
  41. // func 判断是否符合条件
  42. // 如果找到符合条件的元素返回元素指针,否则返回NULL
  43. struct list_elem *list_traversal(struct list *plist, trav_func func, int arg);
  44. // 查找元素是否在链表中,成功返回true,失败返回false
  45. bool elem_find(struct list *plist, struct list_elem *obj_elem);
  46. /****************************** function声明 END ******************************/
  47. #endif // __LIB_KERNEL_LIST_H