I'm trying to implement a circular doubly linked list but I keep getting a segmentation fault: 11 error (I believe it's because of the add and delete functions). I have no idea whether my code is even close, but I can't get past this error to test it properly. This is the class involved:
I see some code for a doubly linked list, but it doesn't appear to be circular. In a circular list, the last node points back to the first one rather than to NULL.
I see you setting next pointers, but not prev pointers.
I see you setting the tail pointer, but not the head pointer. Any time you find yourself changing the tail pointer, there is probably a case where the head pointer changes too.
- in add_to_tail when adding to an empty list
- in delete_from_tail when deleting the last node in the list.
What is line 43 supposed to do?
Line 50: The program will crash if tail is null (i.e., this list is empty).
Thanks heaps for replying
I'm not attempting to point to null, rather trying to set it to null after deleting. Also I'm not supposed to have a head pointer as it's circular, if I need to access head I'm to use tail->next, which is why I'm finding it so tricky.
I'm just going to just delete the last two methods and start again with those.
When I run this, (after commenting out the delete method as it causes the segmentation error) I get an output of '4 1' and can't quite figure out what's causing some to print and others not.
Can you post Circular_DLList.h? It would help if we could see the definition of DLLNode.
Given that there is only a tail pointer, I have these questions:
Line 17: shouldn't you set tail->prev = tail?
Line 20. If the list isn't empty then you need to update
- the new node's prev and next pointers
- the next pointer of the previous node.
- the prev pointer of the next node.
In delete_from_tail, if the list isn't empty then you need to update the prev pointer of the next node and the next pointer of the previous node.
It may help to create diagrams of this stuff. For example, to insert a node, start with a diagram of the two nodes that you're inserting between. Now with a different color, draw the new node and the new links. Write code to change all the links.