#include <stdio.h>
#include <stdlib.h>
struct list_head {
struct list_head *next, *prev;
};
struct node
{
int value;
char name[10];
struct list_head list;
};
typedef struct node NODE;
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)
#define list_entry(link, type, member) \
((type *)((char *)(link)-(unsigned long)(&((type *)0)->member)))
#define list_head(list, type, member) \
list_entry((list)->next, type, member)
#define list_tail(list, type, member) \
list_entry((list)->prev, type, member)
#define list_next(elm, member) \
list_entry((elm)->member.next, typeof(*elm), member)
#define list_for_each_entry(pos, list, member) \
for (pos = list_head(list, typeof(*pos), member); \
&pos->member != (list); \
pos = list_next(pos, member))
static inline void
__list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
static inline void
list_add(struct list_head *new, struct list_head *head)
{
__list_add(new, head, head->next);
}
static inline void
list_add_tail(struct list_head *new, struct list_head *head)
{
__list_add(new, head->prev, head);
}
static inline void
__list_del(struct list_head * prev, struct list_head * next)
{
next->prev = prev;
prev->next = next;
}
static inline void
list_del(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
}
static inline int list_empty(const struct list_head *head)
{
return head->next == head;
}
static inline void __list_del_entry(struct list_head *entry)
{
__list_del(entry->prev, entry->next);
}
static inline void list_move_tail(struct list_head *list,
struct list_head *head)
{
__list_del_entry(list);
list_add_tail(list, head);
}
static inline void list_rotate_left(struct list_head *head)
{
struct list_head *first;
if (!list_empty(head)) {
first = head->next;
list_move_tail(first, head);
}
}
static inline struct list_head *
list_reverse(struct list_head *head)
{
struct list_head *prev = NULL;
struct list_head *cur = NULL;
struct list_head *next = head;
for (; next != NULL; )
{
cur = next;
next = cur->next;
cur->next = prev;
prev = cur;
}
return prev;
}
int
main(int argc, char *argv[])
{
NODE p[30], *cur;
int i, j;
LIST_HEAD(head);
for (i = 0, j = 0; i < 30; i ++, j += 9) {
p[i].value = j;
list_add_tail(&p[i].list, &head);
}
i = 0;
list_for_each_entry(cur, &head, list) {
printf("%d(%d)\n", cur->value, i++);
}
list_reverse(&head);
printf("===========================\n");
list_for_each_entry(cur, &head, list) {
printf("%d\n", cur->value);
}
printf("empty %d\n", list_empty(&head));
return 0;
}
linux内核提取的链表操作函数
最新推荐文章于 2024-07-07 15:59:47 发布