Excellent, the code is following:
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node *link;
struct node {
char data;
link next;
link prev;
};
typedef struct Root *root;
struct Root {
int size;
link first;
link last;
};
root InitList(void);
root AddFront(root list, char value);
link FindNode(root list, char value);
void FindNodeAndDelete(root list, char value);
void DeleteNode(root list, link node);
void PrintList(root list);
int main(void) {
root list;
link node;
list = InitList();
list = AddFront(list, 'M');
list = AddFront(list, 'A');
list = AddFront(list, 'B');
/* This is where segmentation fault occurs */
FindNodeAndDelete(list, 'A');
PrintList(list);
node = FindNode(list, 'A');
/* Ffunction below removes node without any issues*/
/* DeleteNode(list, node); */
PrintList(list);
return 0;
}
root InitList(void) {
root list;
if ((list=(root)malloc(sizeof(root))) == NULL) {
fprintf(stderr, "Not enough memory to allocate root\n");
exit(1);
}
list->first=list->last = NULL;
list->size = 0;
return list;
}
root AddFront(root list, char value) {
link newNode;
if ((newNode=(link)malloc(sizeof(link))) == NULL) {
fprintf(stderr, "Not enough memory to new node\n");
exit(1);
}
if (list->first == NULL) {
newNode->data = value;
newNode->next = list->first;
newNode->prev = NULL;
list->last = newNode;
list->first = newNode;
++list->size;
return list;
}
newNode->data = value;
newNode->next = list->first;
newNode->prev = NULL;
list->first = newNode;
++list->size;
return list;
}
link FindNode(root list, char value) {
link node = NULL;
node = list->first;
if (node == NULL) {
printf("list is empty\n");
return NULL;
}
else {
while (node != NULL) {
if (node->data == value)
return node;
node = node->next;
}
}
printf("Node is not located returning NULL\n");
return NULL;
}
void FindNodeAndDelete(root list, char value) {
link node;
node = FindNode(list, value);
if (node == NULL)
printf("Element is not located\n");
else {
printf("Node located, its value is %c\n", node->data);
node->next->prev = node->prev;
node->prev->next = node->next;
free(node);
}
}
void PrintList(root list) {
link element;
element = list->first;
if (element == NULL)
printf("List is empty\n");
else
while (element != NULL) {
printf("Node's value is %c\n", element->data);
element = element->next;
}
printf("List size is %d\n", list->size);
}
Cheers