Reputation: 3817
I'm teaching myself C and I'm trying to learn the doubly linked list now. Following the book's tutorial, I have found some problems:
typedef struct _seg {
int bits[256];
struct _seg *next, *prev;
} seg;
EXTERN seg *head;
EXTERN seg *last;
Based on codes like this, I know that to go through the linkedlist from head, I can do something like:
seg *p;
p = head;
for ( i = 0; i < k; i++)
p = p->next;
However, how can I reversely go through the linkedlist from the last node(defined as last)?
Upvotes: 0
Views: 418
Reputation: 1
You could reason symmetrically, and code e.g.
seg *p = last;
for (int j=0; j < k && p != NULL; j++)
p = p->prev;
I have added the test p != NULL
to avoid an undefined behavior (when the list has fewer than k
elements; on many systems you would get a segmentation violation crash if you omit the test in that case).
Don't forget to enable all warnings and debugging info when compiling (e.g. compile with gcc -Wall -g
) and learn how to use the debugger (e.g. gdb
).
BTW, C++11 is a different language than C99 or C11 (but with some compatibilities) and offer language support (thru its standard library) for linked lists using std::list.
Upvotes: 2