Data Structures
List Insert
Changing a few next pointers inserts a node at the front or in the middle.
List Insert
list_insert.c
#include <stdio.h>
struct Node {
int value;
struct Node *next;
};
int main(void) {
int insertFront = ;
struct Node second = {20, 0};
struct Node first = {10, &second};
struct Node added = {15, 0};
struct Node *head = &first;
if (insertFront) {
added.next = head;
head = &added;
} else {
added.next = first.next;
first.next = &added;
}
printf("head=%d next=%d\n", head->value, head->next->value);
return 0;
}
#include <stdio.h>
struct Node {
int value;
struct Node *next;
};
int main(void) {
int insertFront = ;
struct Node second = {20, 0};
struct Node first = {10, &second};
struct Node added = {15, 0};
struct Node *head = &first;
if (insertFront) {
added.next = head;
head = &added;
} else {
added.next = first.next;
first.next = &added;
}
printf("head=%d next=%d\n", head->value, head->next->value);
return 0;
}
relink
Insertion saves the old link before pointing a node at the new neighbor.
head update
Inserting at the front changes which node the head pointer references.