summaryrefslogtreecommitdiff
path: root/data_structures
diff options
context:
space:
mode:
Diffstat (limited to 'data_structures')
-rw-r--r--data_structures/linked_list.c98
1 files changed, 98 insertions, 0 deletions
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 <stdio.h>
+#include <stdlib.h>
+
+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;
+}