I have been asked to have a go at 'modifying' a linked list into a doubly linked list. I have had a go but seem to be struggling somewhat with my remove and insert functions.
Any help and advice is much appreciated.
Thanks! I have had a rethink and amended. Now it seems to work as I want but when I step through the destructor I get the following, I have tried to find the problem but can't :( below is my code.
doubly linked list(94838,0x1000d8dc0) malloc: *** error for object 0x1004bf880: pointer being freed was not allocated
doubly linked list(94838,0x1000d8dc0) malloc: *** set a breakpoint in malloc_error_break to debug
In the list code:
lines 100-101: you need to adjust previousnode->next and nextnode->prev
Lines 112-116: You assume the list isn't empty. You also assume there isn't exactly one item, in which case you need to update tail.
Lines 120-124: Same as above
I'm not sure if you're handling all the cases in remove(). I'd structure this as:
- set previousnode to the node before the insertion point. Nullptr means insert at head.
- if (previousnode == nullptr) push_front()
else if (previousnode == tail) push_back()
else you know that there's a node after previousnode. Insert the new node between them.
Thanks I will have a look tomorrow!! If you look at code snippet below, I have commented out a delete. Now it runs with out an error 😂
Haven't got clue why though...
Wait a sec. If idx==0, you remove the first node. If idx == node_count then idx is out of bounds. If idx == node_count-1 then you're removing the tail.
dhayden I have looked at what you said and you are onto something!!
This is going to sound really strange...
When I initialise int node_count{} it is zero. When my fist node is created the node_count is incremented to 1,code runs and reproduces the error.
Now if I init node_count{-1} and increment to zero when first node is created everything is good 🧐, code runs without error.
So where am I going wrong??
I'm not sure if you're handling all the cases in remove(). I'd structure this as:
- set previousnode to the node before the insertion point. Nullptr means insert at head.
- if (previousnode == nullptr) push_front()
else if (previousnode == tail) push_back()
else you know that there's a node after previousnode. Insert the new node between them.
Thanks for all the help. I finally realised that I disappeared down a rabbit hole and was mistaking numbers.size() for the 'indexes' of the nodes. Thanks to dhayden for pointing this out!
I have re-written remove() with the above knowledge in mind.
I have made similar changes to insert().