Список на C. Проблема с удалением элемента. Ошибка в коде
Задача:удалить все слова длиннее последнего. Имеется код но он не работает.
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Node {
char data;
struct Node *next;
};
struct Node *head = NULL;
struct Node *current = NULL;
void addNode(char c) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Error allocating memory\n");
exit(1);
}
newNode->data = c;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
current = newNode;
} else {
current->next = newNode;
current = newNode;
}
}
int main() {
char c;
while ((c = getchar()) != '\n') {
addNode(c);
}
printf("List of words: \n");
current = head;
while (current != NULL) {
printf("%c", current->data);
current = current->next;
}
int end=0, last_word_len = 0;
int curr_word_len = 0;
current = head;
while ( current != NULL) {
c = current->data;
if (!isspace(c) || c != ' ') {
curr_word_len++;
}else{
last_word_len = curr_word_len;
curr_word_len = 0;
}
current = current->next;
}
printf("last word len:%d\t",last_word_len);
//Удаление
curr_word_len = 0;
current = head;
struct Node *prev = NULL;
while (current != NULL) {
c = current->data;
if (!isspace(c) || c != ' ') {
curr_word_len++;
} else {
if (curr_word_len >= last_word_len) {
struct Node *del = current;
for (int i = 0; i < curr_word_len; i++) {
if(prev==NULL)
{
head=current->next;
}
else
{
prev->next = current->next;
}
del = current;
current = current->next;
free(del);
}
} else {
prev = current;
current = current->next;
}
curr_word_len = 0;
}
}
printf("List of words: \n");
current = head;
while (current != NULL) {
printf("%c", current->data);
current = current->next;
}
return 0;
}
К примеру ввели строку он должен удалить все слова больше последнего, но на моменте удаления происходит краш. Кажется проблема в prev и его указателе