I don't understand exactly what new does. This question was sparked after I was told using a vector for nodes didn't work, and I looked at other circularLinkedLists, which seemed to use new.
How does it work, and how do I make a new node with it? From the code I saw, it seemed like there would be no way to reference the new node.
1 2
node *temp=new node;
temp=head;
Isn't this the same as being able to push back a new node into a vector? And wouldn't using a vector be easier to maintain since all the functions for vectors are built into the STL?
eg I can pushback a new node into a vector, so what is so much better about using new?
node *temp=new node;
would reserve enough memory for a `node' object, then call its constructor.
it returns the memory address of that object
so, `temp' will point to this new object, and you may access it by dereferencing the pointer: *temp
now, in your code you inmediately do temp = head; overwritting whatever value was in `temp' and losing all references to that new object (memory leak)
> And wouldn't using a vector be easier to maintain since all the functions for vectors are built into the STL?
¿never heard of std::list or std::forward_llist?
If you store items for a circular linked list in a vector then adding them is easy, but what will you do when you delete an item? To remove the i'th item from a vector, you have to move all items from i+1 to the end down to fill the empty space. And since they've moved, you have to adjust all your pointers.