From a52f63efd443ec92a53509915bc4d8e69b55a51f Mon Sep 17 00:00:00 2001 From: leo Date: Wed, 14 Feb 2024 16:27:12 -0300 Subject: first --- data_structures/linked_list.c | 98 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 data_structures/linked_list.c (limited to 'data_structures') diff --git a/data_structures/linked_list.c b/data_structures/linked_list.c new file mode 100644 index 0000000..b75dfea --- /dev/null +++ b/data_structures/linked_list.c @@ -0,0 +1,98 @@ +#include +#include + +typedef struct Node{ + int value; + struct Node* next; +}list; + +void* create_list(){ + void* ptr = NULL; + return ptr; +} + +void add_node(list **head, int value){ + list *node = (list*)malloc(sizeof(list)); + node->value = value; + node->next = NULL; + + if(*head == NULL){ + *head = node; + }else{ + list *tmp = *head; + while(tmp->next != NULL){ + tmp = tmp->next; + } + tmp->next = node; + } +} + +void print_list(list *head){ + while(head != NULL){ + printf("%d -> ", head->value); + head = head->next; + } + printf("\n"); +} + +void remove_first(list **head){ + list *tmp = *head; + *head = (*head)->next; + free(tmp); +} + +int list_len(list *head){ + int cont = 0; + while(head != NULL){ + cont++; + head = head->next; + } + return cont; +} + +void add_node_pos(list **head, int pos, int value){ + if(pos > list_len(*head)){ + fprintf(stderr, "Posicao nao existe\n"); + return; + } + + list *new_node = (list*)malloc(sizeof(list)); + new_node->value = value; + + if(pos == 0){ + new_node->next = *head; + *head = new_node; + return; + } + + + int cont = 0; + list *f = *head; + list *s = NULL; + while(cont != pos){ + s = f; + f = f->next; + cont++; + } + s->next = new_node; + new_node->next = f; +} + +int main(int argv, char* argc[]){ + list *l = create_list(); + + add_node(&l, 10); + add_node(&l, 20); + add_node(&l, 30); + print_list(l); + add_node_pos(&l, 3, 50); + print_list(l); + add_node_pos(&l, 3, 40); + print_list(l); + add_node_pos(&l, 0, 0); + print_list(l); + add_node_pos(&l, 1, 5); + print_list(l); + + return 0; +} -- cgit v1.2.3