After a lot of effort, I’ve managed to piece together a function that deletes some node from my linked list. But, out of sheer interest, I would like to find out how you can go about deleting the first node from the list, i.e. the head.
My program asks for a letter to delete, so for example.
Hello is stored in the list, the user inputs H for deletion, so that now the list is ello
At the moment with my code, the program crashes obviously as if H is deleted, there is no head, and the program doesn’t know where to go to look for the list.
Below is my current implementation, any clues or hints on how to modify this code( I would like to keep it similar to how I have) to allow Head Node Deletion would be much appreciated!.
EDIT: In response to below
FullList DeleteNode(FullList temp, char c) {
FullList remember;
FullList ptr;
while (temp.head->c != c) {
remember.head = temp.head;
temp.head = temp.head->next;
}
ptr.head = temp.head->next;
free(temp.head);
remember.head->next = ptr.head;
return temp;
}
int main(void) {
FullList List;
char c, s;
List.head = NULL;
while ((c=getchar()) != '.') {
List = addToEnd(List, c);
}
scanf(" %c", &s);
List = DeleteNode(List, s);
while (List.head != NULL) {
printf("%c", List.head->c);
List.head = List.head->next;
}
return 0;
}
typedef struct List {
char c;
struct List *next;
}List;
typedef struct {
List *head;
List *tail;
}FullList;
List *insertList(char c, List *t1) {
List *t = (List*)calloc(1, sizeof(List));
t->c = c ;
t->next = t1;
return t;
}
FullList addToEnd(FullList c, char element) {
if (c.head == NULL) {
c.head = c.tail = insertList(element, NULL);
}else {
c.tail->next = insertList(element, NULL);
c.tail = c.tail->next;
}
return c;
}
void DeleteNode(FullList temp, char c) {
FullList remember;
FullList ptr;
while (temp.head->c != c) {
remember.head = temp.head;
temp.head = temp.head->next;
}
ptr.head = temp.head->next;
free(temp.head);
remember.head->next = ptr.head;
}
int main(void) {
FullList List;
char c, s;
List.head = NULL;
while ((c=getchar()) != '.') {
List = addToEnd(List, c);
}
scanf(" %c", &s);
DeleteNode(List, s);
while (List.head != NULL) {
printf("%c", List.head->c);
List.head = List.head->next;
}
return 0;
}
You can’t do it without changing your existing code.
You’re passing your
FullListstruct to yourDeleteNode()function. This means that any changes to that struct are not visible back inmain– the function is getting a copy of it.You would need to change
DeleteNode()to accept a pointer:Then when calling it
main()you would do:By doing this, you can change the value of
temp->headin your function and it will be visible back inmain()Edit: The logic you’ll need is:
temp->head->c == ctemp->headwithtemp->head->nexttemp->headto a temp pointer*previous. Assigntemp->head->nextto a pointer*current. Loop through the list, moving both pointers. When you find a match incurrent->c, assigncurrent->nexttoprevious->nextandfree()thecurrentnode.