简体   繁体   English

C中的双重链表

[英]Doubly linked list in C

I'm teaching myself C and I'm trying to learn the doubly linked list now. 我正在教自己C,我现在正在努力学习双重链表。 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)? 但是,如何从最后一个节点(定义为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). 我添加了测试p != NULL以避免未定义的行为 (当列表中的元素少于k ;在许多系统上,如果在这种情况下省略测试,则会导致分段违规崩溃)。

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 ). 不要忘记在编译时启用所有警告和调试信息(例如使用gcc -Wall -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 . BTW, C ++ 11是一种与C99或C11不同的语言(但具有一些兼容性),并使用std :: list为链表提供语言支持(通过其标准库)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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