Your
while() loop is also deleting
n2
.
So an easy "fix" is to start from
n2->next
instead of
n2
.
node *cur=n2->next;
That said, your code can be much improved. Some problems:
1) Your program has memory leaks.
In C++, every
new must have a corresponding
delete.
If it doesn't, a "memory leak" occurs. This means that the program will waste memory by not deallocating it when it's no longer needed. It is important to learn early that memory leaks must be avoided in C++.
2) You leave it to the user to build the actual list, by modifying the nodes.
If you want to do this properly, I suggest you read portions of the C++ Tutorial:
http://www.cplusplus.com/doc/tutorial/classes/
http://www.cplusplus.com/doc/tutorial/templates/#class_templates
Your goal would be to create a simple
list class template that offers
insert() and
remove() operations, but never lets the user manually modify the
node's.