简体   繁体   English

C中的链接列表实现选项

[英]Linked List Implementation Options in C

In implementing a single linked list in C, I think there are three ways : 在C中实现单个链表时,我认为有三种方法:

HEADER IS A POINTER ITSELF.IT POINTS TO THE FIRST NODE OF THE LINKED LIST. HEADER是指向链接列表的第一个节点的指示符。

1.Declare the header globally and use function void insert(int) to insert.This should work as header is global. 1.全局声明头部并使用函数void insert(int)进行void insert(int)这应该起到头部全局的作用。

2.Declare header inside main and use function node*insert(node*) to insert.This should work because of the return involved. 2.Declare header in main和use function node*insert(node*) insert.This应该工作,因为涉及的返回。

3.Declare header inside main and use function void insert(node**) to insert. 3.Declare头内的main和使用函数void insert(node**)来插入。

Sometimes the second way works even without the return involved. 有时第二种方式即使没有涉及回报也能有效。 Why? 为什么?

Which is the better way? 哪种方式更好?

If the functions involved are recursive as in tree which method is appropriate? 如果涉及的函数是递归的,就像在树中哪种方法合适?

You should encapsulate your data structure in a single object (the head node or a struct that contains it), and then you can have your functions work on that object. 您应该将数据结构封装在单个对象(头节点或包含它的结构)中,然后您可以让您的函数在该对象上工作。 This means that you can have more than one linked list in your program (that won't work with a global head node) and you can also pass it around to different functions that want to use it (there's no point having a data structure without being able to use it). 这意味着你的程序中可以有多个链表(不适用于全局头节点),你也可以将它传递给想要使用它的不同函数(没有数据结构没有点能够使用它)。

If you have your single object (head node) stored in your program then the insert and delete functions don't need to return anything, as you already have a pointer to the object that represents the linked list. 如果您的程序中存储了单个对象(头节点),则插入和删除函数不需要返回任何内容,因为您已经有一个指向表示链接列表的对象的指针。

If the functions involved are recursive as in tree which method is appropriate? 如果涉及的函数是递归的,就像在树中哪种方法合适?

The functions should not be recursive "as in tree". 这些函数应该像在树中那样递归递归。 The depth of a tree is O(logn), which means recursion is reasonable in many situations; 树的深度是O(logn),这意味着在许多情况下递归是合理的; The size of a linked list is O(n), which means recursion can easily overflow the stack. 链表的大小是O(n),这意味着递归很容易溢出堆栈。

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

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