Example 1 — Insert at head, tail, and position
Start from 1, 2, 3.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
static struct Node *new_node(int value, struct Node *next) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->data = value;
n->next = next;
return n;
}
static void print_list(const struct Node *p) {
for (; p; p = p->next) printf("%d%s", p->data, p->next ? " " : "");
printf("\n");
}
static void free_list(struct Node *p) {
while (p) {
struct Node *t = p->next;
free(p);
p = t;
}
}
static struct Node *insert_tail(struct Node *head, int v) {
if (!head) return new_node(v, NULL);
struct Node *p = head;
while (p->next) p = p->next;
p->next = new_node(v, NULL);
return head;
}
static struct Node *insert_at(struct Node *head, int idx, int v) {
if (idx == 0) return new_node(v, head);
struct Node *p = head;
for (int i = 0; p && i < idx - 1; i++) p = p->next;
if (p) p->next = new_node(v, p->next);
return head;
}
int main(void) {
struct Node *head = new_node(1, new_node(2, new_node(3, NULL)));
head = new_node(0, head); print_list(head);
head = insert_tail(head, 4); print_list(head);
head = insert_at(head, 2, 99); print_list(head);
free_list(head);
return 0;
} How It Works
- Head insertion makes the new node point at the old head.
- Tail insertion walks to the last node and links the new one.
- At index 2 the code stops at node index 1 and splices in
99.
