#include <stdio.h>
#include <malloc.h>
typedef struct Node {
int val;
struct Node* next;
}LinkedList;
void insert_pos(LinkedList**, int, size_t); // 按位插值
void insert_val(LinkedList**, int, int); // 按值插值
void print(LinkedList*); // 打印
void FREE_ALL(LinkedList**); // 释放内存
int main() {
int arr[5] = { 13, 51, 40, 72, 4 }, x, y, z; // 样例
x = 9;
y = 72;
z = 88;
size_t n = 2;
LinkedList* head = NULL, * tail;
// 单链表赋值
for (int i = 4; i > -1; i--) {
tail = head;
head = (LinkedList*)malloc(sizeof(LinkedList));
if (head) {
head->val = arr[i];
head->next = tail;
}
}
printf("初始链表:");
print(head);
// 按位插入值
insert_pos(&head, x, n);
printf("在第 %lu 位插入值 %d:", n, x);
print(head);
// 按值插入值
insert_val(&head, y, z);
printf("按值 %d 之后插入值 %d:", y, z);
print(head);
// 释放内存
FREE_ALL(&head);
return 0;
}
void insert_pos(LinkedList** head, int val, size_t N) {
LinkedList* p, * temp;
if (*head) {
p = (*head);
if (N) while (p && --N) p = p->next;
temp = (LinkedList*)malloc(sizeof(LinkedList));
if (temp && p) {
temp->val = val;
temp->next = p->next;
p->next = temp;
}
}
else {
printf("linked list is empty\n");
}
}
void insert_val(LinkedList** head, int valA, int valB) {
LinkedList* p, * temp;
if (*head) {
p = (*head);
if (p) while (p && (p->val != valA)) p = p->next;
temp = (LinkedList*)malloc(sizeof(LinkedList));
if (temp && p) {
temp->val = valB;
temp->next = p->next;
p->next = temp;
}
}
else {
printf("linked list is empty\n");
}
}
void print(LinkedList* head) {
if (head) {
while (head) {
printf("%d ", head->val);
head = head->next;
}
}
printf("\n");
}
void FREE_ALL(LinkedList** head) {
LinkedList* p;
if (*head) {
while (*head) {
p = (*head);
(*head) = (*head)->next;
free(p);
}
}
free(*head);
}