Re: Could anyone explain the code for me?

From: Cy Edmunds (cedmunds_at_spamless.rochester.rr.com)
Date: 01/04/04


Date: Sun, 04 Jan 2004 03:12:59 GMT


"C++fan" <jw2000@excite.com> wrote in message
news:15c9b1f2.0401021524.77d34ce6@posting.google.com...
> The following code is for list operation. But I can not understand.
> Could anyone explain the code for me?
>
> /*
> * List definitions.
> */
>
> #define LIST_HEAD(name, type)
> struct name {
> type *lh_first; /* first element */
> }
> #define LIST_ENTRY(type)
> struct {
> type *le_next; /* next element */
> type **le_prev; /* address of previous next element */
> }
>
> Questions:
> Why the struct does not have a name?
> Is the list a two-way list?
>
> /*
> * List functions.
> */
> #define LIST_INIT(head) {
> (head)->lh_first = NULL;
> }
>
> #define LIST_INSERT_AFTER(listelm, elm, field) {
> if (((elm)->field.le_next = (listelm)->field.le_next) != NULL)
> (listelm)->field.le_next->field.le_prev =
> &(elm)->field.le_next;
> (listelm)->field.le_next = (elm);
> (elm)->field.le_prev = &(listelm)->field.le_next;
> }
>
> Question:
> What is listelm, elm, field?
>
> #define LIST_INSERT_HEAD(head, elm, field) {
> if (((elm)->field.le_next = (head)->lh_first) != NULL)
> (head)->lh_first->field.le_prev =
> &(elm)->field.le_next;
> (head)->lh_first = (elm);
> (elm)->field.le_prev = &(head)->lh_first;
> }
>
> Question:
>
> If elm becomes head, what's the purpose of the last sentence:
> (elm)->field.le_prev = &(head)->lh_first;
>
>
> Thanks in advance.
>
> Jack

Here is some tested code. I still hate it. :)

struct list_node
{
 LIST_ENTRY(list_node) node;
 int thing;
};

void list_test()
{
 LIST_HEAD(t_head, list_node) mylist;
 LIST_INIT(&mylist);
 list_node *p1 = new list_node;
 p1->thing = 24;
 LIST_INSERT_HEAD(&mylist, p1, node);
 list_node *p2 = new list_node;
 p2->thing = -3;
 LIST_INSERT_AFTER(p1, p2, node);

 list_node *p3 = mylist.lh_first;
 while (p3 != 0)
 {
  std::cout << p3->thing << '\n';
  p3 = p3->node.le_next;
 }

 delete p2;
 delete p1;
}

Output is:

24
-3

-- 
Cy
http://home.rochester.rr.com/cyhome/


Relevant Pages