#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int x;
struct Node *next;
} Node;
void add_first(Node **root, int value) {
Node *new_node = malloc(sizeof(int));
if (new_node == NULL) {
puts("malloc error");
exit(1);
}
new_node->x = value;
new_node->next = *root;
*root = new_node;
}
void add_after(Node *node, int value) {
Node* new_node = malloc(sizeof(Node));
if (new_node == NULL) {
puts("malloc error");
exit(1);
}
new_node->x = value;
new_node->next = node->next;
node->next = new_node;
}
void add_sorted(Node **root, int value) {
if (*root == NULL || (*root)->x >= value) {
printf("add_first value %d\n", value);
add_first(root, value);
return;
}
Node *current = *root;
while (current->next != NULL) {
if (current->next->x >= value) {
printf("current->x %d add_after value %d\n", current->x, value);
add_after(current, value);
return;
}
current = current->next;
}
printf("current->x %d add_afte value %d\n", current->x, value);
add_after(current, value);
}
void add_node(Node **root, int value) {
Node *new_node = malloc(sizeof(Node));
if (new_node == NULL) {
puts("malloc error");
exit(1);
}
new_node->next = NULL;
new_node->x = value;
if (*root == NULL) {
*root = new_node;
return;
}
Node* current = *root;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
void free_LinkedList(Node *root) {
Node *next;
while (root != NULL) {
next = root->next;
free(root);
root = next;
}
}
int main() {
Node *root = NULL;
add_sorted(&root, 7);
add_sorted(&root, 2000);
add_sorted(&root, 78);
add_sorted(&root, 3);
for (Node *current = root; current != NULL; current = current->next) {
printf("%d\n", current->x);
}
free_LinkedList(root);
return 0;
}
/*
run:
add_first value 7
current->x 7 add_afte value 2000
current->x 7 add_after value 78
add_first value 3
3
7
78
2000
*/