Keeping track of the tail can help in some situations, but here the main issue is that the list traversal loop at lines 32-38 is not keeping track of the previous node. At this point you don't need the next one (that's available as a member of the current node) but you do need the previous node.
This is because when you delete the node you found (ignoring the head node for the moment) you've got to set the previous node's next to the next of the node you're just about to delete (which will be null it you're deleting the current last link.)
(Talking of delete, I don't see any unwanted nodes being deleted?)
Actually, looking at lines 50, 51 I see
you're not actually removing the found node; instead you're copying the contents of the next node over to the found node and throwing the next node away (consequently leaking the old next node's memory.)
There should be no copying of the value at this point; just relinking of the nodes (and a delete!) As it's just an int you're copying here it's cheap, but if this was was a bulky data object the copy operation could cost!
And I think you are complicating things a bit by the way you are using
traversalNode->next == NULL
to test whether a node has been found or not. Using
traversalNode == NULL
and the previous node works for me with no special casing for last node.
Andy
PS
1. Can the list ever be empty? (i.e. have no head node?) If so, then line 21 could crash your program.
2. I see you class provides a "find" method, though the parameter name implies that it's intended to return the i'th entry rather actually find something. Or is the value of index compared against the item member of the SinglyLinkedListNode structs? You could split deleteNumber into a find operation (which could be used elsewhere) and the actual node removal.
3. Lines 17 and 18 of your code don't look quite right?
17 18
|
SinglyLinkedListNode * nextNode = new SinglyLinkedListNode;
SinglyLinkedListNode * traversalNode = new SinglyLinkedListNode;
|
After creating the two new nodes you are then trampling on them (so you're leaking memory.) A cut and paste-ism??