Linked list removing problem [repost from r cplusplus]

Hello, here I have a program which takes in the head of a linked list and the value that I want the node removed. It successfully removes and returns the head if the data exists. If data doesnt exist, I want to return the original head and https://www.acesetm.biz/ , although for some reason the program crashes. If I remove everything inside the if(current->next-data... (line20) , it returns perfectly. Can someone please help? thank you!

Node* remove(Node* head, int data)
{
if (head == NULL)
{
return head;
}
else
{
Node* current = head;
if(current->data == data)
{
head = current->next;
delete current;
return head;
}
else
{
while(current != NULL)
{
if(current->next->data == data)
{
Node* temp = current->next;
current->next = temp->next;
delete temp;
return head;
}
current = current->next;
}
return head;
}
}
}
Last edited on
You need to use https://www.cplusplus.com/articles/jEywvCM9/ if you're posting code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Node *remove(Node * head, int data)
{
  if (head == NULL) {
    return head;
  } else {
    Node *current = head;
    if (current->data == data) {
      head = current->next;
      delete current;
      return head;
    } else {
      while (current != NULL) {
        if (current->next->data == data) {
          Node *temp = current->next;
          current->next = temp->next;
          delete temp;
          return head;
        }
        current = current->next;
      }
      return head;
    }
  }
}


> if (current->next->data == data)
current may be non-null, but on the last node, current->next will be null and you're screwed.


Using a prev pointer:
1
2
3
4
5
6
7
8
9
10
11
12
    for (Node *current=head, *prev=nullptr; current; prev=current, current = current->next) {
        if (current->data == data) {
            if (prev) {
                prev->next = current->next;
            } else {
                head = current->next;
            }
            delete current;
            break;
        }
    }
    return head;


Using a head-or-next pointer:
1
2
3
4
5
6
7
8
9
    Node *current, **headOrNext;
    for (headOrNext = &head; (current = *headOrNext); headOrNext = &current->next) {
        if (current->data == data) {
            *headOrNext = current->next;
            delete current;
            break;
        }
    }
    return head;

Topic archived. No new replies allowed.