带头节点的链表。
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* NewNode(int data) {
Node* node = malloc(sizeof(Node));
node->data = data, node->next = NULL;
return node;
}
Node* NewHead(void) {
return NewNode(0);
}
void Append(Node* head, int data) {
Node* node = NewNode(data);
while (head->next)
head = head->next;
head->next = node;
}
void Prepend(Node* head, int data) {
Node* node = NewNode(data);
node->next = head->next;
head->next = node;
}
void Insert(Node* head, int data, int ndx) {
Node* node = NewNode(data);
for (int i = 0; i < ndx && head; i++)
head = head->next;
if (head)
node->next = head->next, head->next = node;
}
void Remove(Node* head, int data) {
Node* prev = head;
head = head->next;
while (head && head->data != data)
prev = head, head = head->next;
if (head) {
prev->next = head->next;
free(head);
}
}
void RemoveAll(Node* head, int data) {
Node* prev = head;
head = head->next;
while (head)
if (head->data != data) {
prev->next = head;
prev = head;
head = head->next;
} else {
Node* q = head;
head = head->next;
free(q);
}
}
Node* Find(Node* head, int data) {
head = head->next;
while (head && head->data != data)
head = head->next;
return head;
}
Node* Reverse(const Node* head) {
Node* new_head = NewHead();
while (head->next) {
Node* t = head->next;
head->next = head->next->next;
t->next = new_head->next;
new_head->next = t;
}
return new_head;
}
int Count(const Node* head) {
int count = 0;
while ((head = head->next))
count++;
return count;
}
Node* NewFromArray(const int arr[], int len) {
Node* head = NewHead();
Node* p = head;
for (int i = 0; i < len; i++)
p = p->next = NewNode(arr[i]);
return head;
}
void Dump(const Node* head) {
head = head->next;
while (head) {
printf("%d ", head->data);
head = head->next;
}
putchar('\n');
}