환형 리스트를 범용적으로 구현..

2007/11/27 17:40

List를 C로만 구성하기 위해서 공개된 list 를 참고해 본다.
일단  http://lxr.linux.no/source/include/linux/list.h 를 참조.

1. 보통 리스트를 구현할 때 리스트와 자료형을 같이 사용하지만 이런 구현은 매번 리스트를 따로 구현해야하는 아픔이 있다.


2. 그래서 리스트의 구조를 구조체를 만들때 그 밑에 구현 해 놓는 방식을 사용하도록 한다.
3. 이렇게 되면 리스트를 포함 시켜놓으면 헤더 파일을 중심으로 리스트를 가질수 있다.


4. 리스트의 추가는 앞뒤의 객체에게 알려주면 된다.
void __list_add(struct list_head *new=0x3004,

            struct list_head *prev=0x1000,

            struct list_head *next=0x2004)

{

  next->prev = new;

  new->next = next;

  new->prev = prev;

  prev->next = new;

}


5. 구조체의 내용을 읽기 위해선 시작위치를 0으로 시작한다는 개념을 잡아야 한다. 

#define  list_entry( temp, type, list ) \

((type *)((char*)temp (unsigned long)(&((type *)0)->list)))

TASK *p = list_entry( temp, TASK, list );

p->pid;


전체 소스 ~

[ more.. | less.. ]
#include <stdio.h>

struct list_head
{
    struct list_head *next;
    struct list_head *prev;
};

typedef struct
{
    int count;
    int pid;
    struct list_head list;
} TASK;

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;
}

void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}

#define  list_entry( temp, type, list ) \
    ((type *)( (char*)temp - (unsigned long)(&((type *)0)->list)))

#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next )

#define LIST_HEAD_INIT(name) { &(name), &(name) }

#define LIST_HEAD(name) \
struct list_head name = LIST_HEAD_INIT(name)

int main()
{
    struct list_head *temp;
    LIST_HEAD(head);

    TASK  t1 = { 1, 1000, 0, 0 };
    TASK  t2 = { 2, 2000, 0, 0 };
    TASK *p;

    list_add ( &t1.list, &head );
    list_add ( &t2.list, &head );

    printf("[head]");
    list_for_each( temp, &head )
    {
        p = list_entry( temp, TASK, list );
        printf("->[%4d, %4d]",p->count, p->pid);
    }
    printf("\n");
    return 0;
}

Tags

list, 자료구조