I'm working on learning linked lists and I've written a program with various functions to create and manipulate the list, one of them being:
void DeleteNode(int x) {
struct Node* temp = head;
struct Node* prevptr = temp->prev;
struct Node* nextptr = temp->next;
if(temp == NULL) return;
while(temp->data != x) {
temp = temp->next;
}
prevptr->next = temp->next;
nextptr->prev = temp->prev;
free(temp);
}
When I run my main function:
int main() {
InsertAtHead(2); Print();
InsertAtHead(1); Print();
InsertAtTail(3); Print();
InsertAtTail(4); Print();
DeleteNode(3); Print();
}
The output looks like:
Forward: 2
Forward: 1 2
Forward: 1 2 3
Forward: 1 2 3 4
Segmentation fault (core dumped)
I imagine this means that I've lost the list somewhere in the process of trying to delete a node but can't figure out how. What am I doing wrong here?
prevptr = temp->prev;:prevptrisNULL. ..prevptr->next = temp->next;:NULL->nextmight occurs seg-fault. Alsowhile(temp->data != x) {-->while(temp && temp->data != x) {