How to implement a linked list in C?

后端 未结 14 864
予麋鹿
予麋鹿 2020-12-06 02:49

I am creating a linked list as in the previous question I asked. I have found that the best way to develop the linked list is to have the head and tail in another structure.

14条回答
  •  死守一世寂寞
    2020-12-06 03:27

    You're allocating the wrong chunk of memory. Instead of allocating memory for each list element, you're allocating for the list head and tail.

    For simplicity, get rid of the separate structure for the head and tail. Make them global variables (the same scope they're in now) and change them to be listhead and listtail. This will make the code much more readable (you won't be needlessly going through a separate structure) and you won't make the mistake of allocating for the wrong struct.

    You don't need a tail pointer unless you're going to make a doubly linked list. Its not a major element to add once you create a linked list, but not necessary either.

提交回复
热议问题