Code:
void removemiddle(node *&x)
{
node *c;
c=x->next;
x=c->next;
delete c;
}
You pass the pointer by reference. Either pass the reference of x (node& x) or pass the pointer (node* x). You have in your code node* x = first; and then removemiddle(x); so you want void removemiddle(node* x).
Also, the logic is wrong. You want this:
Code:
void removemiddle(node *x)
{
node* prev;
//find previous node from x
for (prev = head; prev != NULL; prev = prev ->next
if ( prev ->next == x)
break;
if (prev == NULL) {
printf("The node doesn't exist in list");
return;
}
// You have [prev] -> [x] -> [x->next]
//link the previous o x node with the next of x node
prev->next = x->next;
// Now you have [prev] -> [x->next]
//delete safely x
delete x;
}
Now, finding the middle node of course isn't a good idea. But WAIT. You knew this. So you pass the previous node as I see. Well, it is a good idea to give GOOD NAMES! This would have saved me the trouble
Code:
void removemiddle(node *prevNode)
So in your case:
Code:
void removemiddle(node *prevNode)
{
// You have [prevNode] -> [prevNode->next] -> [prevNode->next->next]
//link the previous o x node with the next of x node
prevNode->next = prevNode->next->next;
// Now you have [prevNode] -> [prevNode->next->next]
//delete safely prevNode->next
delete prevNode->next ;
}
Finally, since this is C++, you could make a class and pout the removes functions inside the class. That would make your code much cleaner. You would have a class node and a class list. The list class would only have a node* head, tail and the remove/add functions. So you would check if it is the middle, head or tail (by comparing with head or tail). You could just do "list.Remove(char a)" and the correct method/function would be invoked. Try it.
Also, do you actually need the tail? Tail makes sense in a double linked list. Otherwise not really. Because you can find which is the tail. It is the node that has next == NULL and only that. So you don't need the tail