summaryrefslogtreecommitdiff
path: root/data_structures/linked_list.c
blob: b75dfea6a45b604d51e549d34cf349ea88af9d80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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;
}