/**
* Author: Ozan Özenoğlu
* Date : 16/10/2020
* */
struct linked_list_node {
struct linked_list_node *next;
int val;
};
typedef struct linked_list_node linked_list_node_t;
struct linked_list {
int size;
linked_list_node_t *head;
};
typedef struct linked_list linked_list_t;
void init(linked_list_t *list){
list->size = 0;
list->head = (void*)0;
printf("linked list init completed\n");
}
void add(linked_list_t *list, int val){
linked_list_node_t *node = malloc(sizeof(linked_list_node_t)*1);
node->val = val;
node->next = list->head;
list->head = node;
list->size++;
printf("%d is added\n",val);
}
void insert_node_to_position(linked_list_node_t *node, linked_list_t * l) {
linked_list_node_t * h = l->head;
linked_list_node_t * current;
linked_list_node_t * previous;
linked_list_node_t *new_node = malloc(sizeof(linked_list_node_t));
new_node->val = node->val;
new_node->next = (void*)0;
current = h;
previous = h;
if (current == (void*)0) { // if it's first element to sorted list.
printf("First node %d\n", node->val);
l->head = new_node;
return;
}
if (new_node->val < h->val) {
linked_list_node_t *tmp = l->head;
l->head = new_node;
new_node->next = tmp;
printf("Added to begining %d\n", new_node->val);
}
else {
while(current != (void*)0 && new_node->val > current->val) {
printf("node val %d > current val %d\n",new_node->val, current->val);
previous = current;
current = current->next;
}
previous->next = new_node;
new_node->next = current;
}
}
linked_list_t *insertation_sort(linked_list_t *l) {
linked_list_t * sorted_list = malloc(sizeof(linked_list_t)*1);
sorted_list->head = (void*)0;
sorted_list->size = 0;
linked_list_node_t *node = l->head;
while(node != (void*)0) {
printf("insert node %d\n", node->val);
insert_node_to_position(node , sorted_list);
print_list(sorted_list);
node = node->next;
}
return sorted_list;
}
int main() {
linked_list_t my_list;
init(&my_list);
add(&my_list, 5);
add(&my_list, 123);
add(&my_list, 1);
add(&my_list, 4);
add(&my_list, 3);
add(&my_list, 2);
print_list(&my_list);
/*
linked_list_t * sorted_list = insertation_sort(&my_list);
print_list(sorted_list);
return 0;
}