简体   繁体   中英

Linked List Implementation Options in C

In implementing a single linked list in C, I think there are three ways :

HEADER IS A POINTER ITSELF.IT POINTS TO THE FIRST NODE OF THE LINKED LIST.

1.Declare the header globally and use function void insert(int) to insert.This should work as header is global.

2.Declare header inside main and use function node*insert(node*) to insert.This should work because of the return involved.

3.Declare header inside main and use function void insert(node**) to insert.

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; The size of a linked list is O(n), which means recursion can easily overflow the stack.

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