Data Structures
List Remove
Removing a linked node changes the previous node to skip over it.
List Remove
list_remove.c
#include <stdio.h>
struct Node {
int value;
struct Node *next;
};
int main(void) {
int removeValue = ;
struct Node third = {30, 0};
struct Node second = {20, &third};
struct Node first = {10, &second};
struct Node *head = &first;
struct Node *previous = 0;
struct Node *current = head;
int removed = 0;
while (current != 0 && removed == 0) {
if (current->value == removeValue) {
if (previous == 0) {
head = current->next;
} else {
previous->next = current->next;
}
removed = 1;
} else {
previous = current;
current = current->next;
}
}
printf("removed=%d head=%d\n", removed, head->value);
return 0;
}
#include <stdio.h>
struct Node {
int value;
struct Node *next;
};
int main(void) {
int removeValue = ;
struct Node third = {30, 0};
struct Node second = {20, &third};
struct Node first = {10, &second};
struct Node *head = &first;
struct Node *previous = 0;
struct Node *current = head;
int removed = 0;
while (current != 0 && removed == 0) {
if (current->value == removeValue) {
if (previous == 0) {
head = current->next;
} else {
previous->next = current->next;
}
removed = 1;
} else {
previous = current;
current = current->next;
}
}
printf("removed=%d head=%d\n", removed, head->value);
return 0;
}
#include <stdio.h>
struct Node {
int value;
struct Node *next;
};
int main(void) {
int removeValue = ;
struct Node third = {30, 0};
struct Node second = {20, &third};
struct Node first = {10, &second};
struct Node *head = &first;
struct Node *previous = 0;
struct Node *current = head;
int removed = 0;
while (current != 0 && removed == 0) {
if (current->value == removeValue) {
if (previous == 0) {
head = current->next;
} else {
previous->next = current->next;
}
removed = 1;
} else {
previous = current;
current = current->next;
}
}
printf("removed=%d head=%d\n", removed, head->value);
return 0;
}
previous pointer
The previous node is needed so its link can bypass the removed node.
removed flag
A flag records whether the target value was found.