I think you have a basic misconception. Here is what your linked list should look like:
[head] -> [value1, link1] -> [value2, link2] -> ...
The head should only be a link
(i.e. pointer) to the first node
. You correctly coded, that if (head == NULL)
create a new node
and make start
(i.e. head
) point to that node. So you would have:
[head] -> [value1, link1]
Now on your else
block, which runs when there is already a head
, you create a new node
, you give it a value, and you make its link
point to head. And here are your mistakes.
Firstly, no node
will point to this node
, so you effectively haven't added it to the list. Moreover, even if you wanted it to be the head
, by the time you make this node
the head
, you lose the other head
and effectively all the other nodes behind it. And you also make this node, point to itself. See here:
curr-> link = start;
start = curr;
Here is how the linked list should work. Say we already have the following list:
[head] -> [value1, link1] -> [value2, link2]
- To append at the end of the list, you must create a new
node
(let's call it node3
).
- Give a value to this
node
's value
variable.
- Then make
link3
point to NULL
, to be sure it's initialized.
- Then make
link2
point to node3
.
Then you would have the following:
[head] -> [value1, link1] -> [value2, link2] -> [value3, link3]
Now say you want to add a node
at the beginning of the list. Here's what you should do:
- Create a new
node
(let's call it node4
).
- Give a value to this
node
's value
variable.
- Make
link4
point to node1
, so that you don't lose all the members of the list.
- Make
head
point to node4
Then you would have the following:
[head] -> [value4, link4] -> [value1, link1] -> [value2, link2] -> [value3, link3]
Tip #1
The word print
is in some languages a reserved word or a function, so you should better rename the variable in your print()
function. You should also not use the same name for both a function and a variable. It makes your code unreadable. Rename the function to printList()
and the variable to nodeToPrint
or currentNode
.
If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!