Question about deleting Node by value function.

So I made this function to delete node by value. But if the value of the node that I'm trying to delete doesn't exist, it crashes. Does anyone know how to fix that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void deltarget (int value)
{

    if (front -> item == value)
        {
        Node *temp = front;
        temp = temp -> next;
        temp -> prev = NULL;
        front = temp;
        }
    else
    {
        Node *temp = front;
        while(temp -> item != value)
        {
            temp = temp -> next;
        }
        temp -> next -> prev = temp -> prev;
        temp -> prev -> next = temp -> next;
        delete temp;
    }
You have to check to see if you reached the end of the list. And if you have, then stop searching and don't try to delete any node.


Also, if the matching node is 'front', you are leaking memory because you aren't deleteing the front node.
Last edited on
Even after doing that, it crashes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void deltarget (int value)
{

    if (front -> item == value)
        {
        Node *temp = front;
        temp = temp -> next;
        temp -> prev = NULL;
        delete front;
        front = temp;
        }
    else if (tail -> item == value)
    {
        Node *temp = tail;
        temp -> prev -> next = NULL;
        temp = temp -> prev;
        delete tail;
        tail = temp;
    }
    else
    {
        Node *temp = front;
        while(temp -> item != value && temp -> next != NULL)
        {
            temp = temp -> next;
        }
        temp -> next -> prev = temp -> prev;
        temp -> prev -> next = temp -> next;
        delete temp;
    }
Last edited on
Topic archived. No new replies allowed.