0

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?

6
  • I assume that when you wrote "header", what you meant was the head node of the list. The question is quite confusing. Commented Sep 21, 2013 at 17:04
  • node* is an implementation detail that should not be part of the interface of the list. Commented Sep 21, 2013 at 17:04
  • @LihO header is a dummy node containing no data. Commented Sep 21, 2013 at 17:07
  • It will work if you don't change the head in the node *insert(node *). Commented Sep 21, 2013 at 17:09
  • when insert(node*) acts on header which is a pointer itself, then?? will it work without return type? Commented Sep 21, 2013 at 17:11

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

when header is a dummy node it 2nd way should work.When header is a pointer itself then should it work without return type?
Create two structs, one called node and one called list. The list struct has a node pointer, which can be NULL for an empty list. Even for an empty list, the list node should exist. Now you have no need for dummy nodes.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.