linked list: problem in deleting a node

If p is a pointer pointing a node to be deleted, then what's wrong in the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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";
        }

where a is a struct.
Last edited on
closed account (zb0S216C)
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
  }

Wazzak
Last edited on
Thanks!
Topic archived. No new replies allowed.