Why am I getting an arbitrary output on the place of the deleted element ? Please help.
Below is the function I wrote
LINKED LIST: 4 3 2
RESULT: 4 3 16608944 NULL
Draw pictures until you get a feel for this stuff.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
a list:
1-2-3-4-5-N
H
T
initially, after tmp = head... you have the above.
you loop a bit, and eventually tmp->next is null (N)
1-2-3-4-5-N
H T
so tail = tmp = the 5 in thiscase.
delete tmp. tail and tmp are both now invalid. now what?
then loop ends and tmp = invalid->next. what?
so what needs to happen?
here,
you need to set 4's next to null.
you need to delete 5.
it needs to work if there are 0, 1, and 2+ items in your list. in these cases you don't have next->next as a way to find the 5 while holding onto the 4. it must handle all these cases!
so what do you do when head == null, or the lists look like these
1 //delete the one and only element and set head to null
1 - 2 //delete the 2 and head-> next is null
1 - 2 - 3 //this is the more normal case that I already said.