cout << "Do you want to delete this record? (y/n) ";
if (getch() == 'y' || getch() == 'Y'){// Delete record.
if (p == *ph){//If first node is to be deleted.
*ph = (*ph)->next;
delete p;
}
else{
a *b = *ph;
while (b->next!=p){
b = b->next;
}//Now b is just before p.
b->next = b->next->next;
delete p;
//p = NULL;
}
system("cls");
}
else
cout << "Another";
}
Assuming your code is not a doubly-linked list, then your problem is pointing to the to-be-deleted-node. Why? When you "delete" the target node, you lose all information about that node, including where the subsequent node (if any) is located. What you need to do in singular-linked list implementations is point to the node before the target node. This way, you can delete the target node through the pointed-to node's link data-member. For instance:
struct Node
{
int Data_;
Node *Subsequent;
};
struct List
{
Node *Root;
void Remove_Node( Node *Node_Before )
{
// Keep track of the node pointed-to by the to-be-removed node:
Node * const Node_After( Node_Before->Subseqent->Subsequent );
// Remove the to-be-deleted node:
delete Node_Before->Subsequent;
// Link the two nodes on either side of the once-removed node:
Node_Before_->Subsequent = Node_After;
}
};
If you want to remove the very first node, then you need to keep track of the second node:
1 2 3 4 5 6 7 8 9 10 11
void Remove_First_Node( )
{
// Keep track of the second node:
Node * const Node_After( Root->Subsequent );
// Remove the first node:
delete Root;
// Set the second node as the first node:
Root = Node_After;
}