简体   繁体   中英

Doubly linked list in C

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)?

You could reason symmetrically, and code eg

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 (eg compile with gcc -Wall -g ) and learn how to use the debugger (eg 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM