2

I have met two ways to implement double linked list:

#define LIST_ENTRY(type)                        \
  struct {                              \
      struct type *le_next; /* next element */          \
      struct type **le_prev;    /* address of previous next element */  \
}

this way is in the FreeBsd queue.h,I want to know why it uses a pointer to pointer le_prev?

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

this way is in the linux list.h, it just uses two simple pointers.

What is the difference? Which is better, just use a simple pointer and a pointer to pointer or two simple pointers?

nj-ath
  • 3,028
  • 2
  • 25
  • 41
karllo
  • 341
  • 3
  • 10
  • It depends upon semantics.Single pointers will just point to a previous or next node or element on the other hand double pointers can be used where your pointers will again be pointing to a linked list containing other nodes. – Naseer Nov 14 '14 at 08:55
  • Are you sure the double pointer is for a "previous next element"? – nj-ath Nov 14 '14 at 08:57
  • http://cvsweb.netbsd.org/bsdweb.cgi/src/sys/sys/queue.h?rev=1.30 – Ivan Ivanovich Nov 14 '14 at 09:00
  • http://stackoverflow.com/questions/16440601/why-does-the-doubly-linked-list-in-sys-queue-h-maintain-the-address-of-previous – Ivan Ivanovich Nov 14 '14 at 08:59

1 Answers1

1

The list is not "doubly-linked", in the sense that the list is not traversable in both directions. The double pointer is given so that the next pointer can be changed quickly.

Also, in c, structure elements are always stored contiguously. So given the address of next pointer, you can calculate the address of the previous node. But this simply adds complexity in the code and requires you to calculate the size of all elements in the structure. It's not worth the trouble. (You should not assume this and say that it's a linked list with 2-side traversal)

Which is better?

Implementation with two simple pointers is generally better. There might be special situations where double-pointer implementation might be better.

nj-ath
  • 3,028
  • 2
  • 25
  • 41
  • "So given the address of next pointer, you can calculate the address of the previous node." Are you assuming that the elements of the list are stored in an array? – Étienne Nov 14 '14 at 12:48
  • next pointer in the sense "next" element(in the structure). I'm not saying next node of the linked list – nj-ath Nov 14 '14 at 12:56