I have understood how deletion works in linked list, however the implementation is harder than I thought. I have written this below but it is not working sadly
My node:
struct DLinkedList
{
double sensorData;
struct DLinkedList *prev;
struct DLinkedList *next;
};
And this is my delete function:
void delete(struct DLinkedList **first, struct DLinkedList *el)
{
struct DLinkedList* temp = *first;
if (temp != NULL && temp->sensorData == el->sensorData)
{
(*first) = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->sensorData == el->sensorData)
{
temp->prev = temp;
temp = temp->next;
}
if (temp == NULL)
{
return;
}
free(temp);
}
Is there something wrong with the code itself? The compiler is not giving me any errors but the function doesn't seem to work properly, the way I call it in main() is delete(&first, el);
Here is my main, I have added 3 elements excluding el
so that I can see the list more clearly:
int main()
{
//Adding 3 nodes
struct DLinkedList* first = NULL;
struct DLinkedList* second = NULL;
struct DLinkedList* last = NULL;
struct DLinkedList* el = NULL;
//Allocating 3 nodes
first = malloc(sizeof(struct DLinkedList));
second = malloc(sizeof(struct DLinkedList));
last = malloc(sizeof(struct DLinkedList));
el = malloc(sizeof(struct DLinkedList));
first->sensorData = 1; //Assigning data for 'first' node
first->next = second; //Link first node with second node
first->prev = NULL;
second->sensorData = 2;
second->next = last;
second->prev = first;
last->sensorData = 3;
last->next = NULL;
last->prev = second;
el->sensorData = 10;
el->next = first;
el->prev = NULL;
insertFirst(&first, el);
printList(first);
isMember(&first, el);
delete(&first, el);
return 0;
}
//Printing contents of the linked list starting from the 'first' node
void printList(struct Node* first)
{
while (first != NULL)
{
printf(" %f ", first->data);
first = first->next;
}
}
Here below is my minimal example, I have made some changes in the names and main in order to be more readable
#include <stdio.h>
#include <stdlib.h>
//A linked list node
struct Node
{
double data;
struct Node* prev;
struct Node* next;
};
void delete(struct Node** first, struct Node* el)
{
if (*first == el)
{
*first = el->next;
}
if (el->prev)
{
el->prev->next = el->next;
}
if (el->next)
{
el->next->prev = el->prev;
}
free(el);
}
int main()
{
struct Node* first = NULL;
struct Node* el = NULL;
el = malloc(sizeof(struct Node));
el->data = 10;
el->next = NULL;
el->prev = NULL;
delete(&first, el);
print(first);
return 0;
}