Hello everybody. I have build a code which creates and displays list of cylinders which contains 10 elements. Now my task is to build an additional functions that removes the last element of the list. Could somebody please show me how it could be done with the most basic idea?
Since you have a singly linked list, you have to walk the list until you find the last entry (next == 0). Save the pointer to the previous entry as you go. delete prev->next, then set prev->next = 0.
Other comments:
- add_to_list only works when the list isn't empty.
- It's inefficient to add to the back of a linked list. You should add to the front instead.
- No need to create the typedef for cylinder. If you want to use cylinder instead of Cylinder then just say struct cylinder { ... };
- create_cylinder() should be cylinder's constructor. It should set the next pointer too.
- Use a for loop for display_list:
dhayden, it tells me that nullptr is not declared in this scope. Also I'm not familiar with this operate type. Can you tell me what could the problem be?
In your original code you used 0 as a null pointer constant, which works, but could be confused for an integer. C++11 added nullptr but if you compiler is too old to support it, and you don't feel like upgrading, you could just replace it with 0 (or NULL).