summaryrefslogtreecommitdiff
path: root/linked_list.c
blob: 792da4d39fa6259f82a7c8c43c5cd20b119c42ee (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
#include <stdlib.h>
#include "linked_list.h"

linked_list *add_node(linked_list **tail, void *data) {
	if (tail == NULL) {
		return NULL;
	} else {
		linked_list *node = calloc(1, sizeof(linked_list));
		if (node == NULL) {
			return NULL;
		} else {
			node->next = NULL;
			node->data = data;

			if (*tail == NULL) {
				node->prev = NULL;
				*tail = node;
			} else {
				(*tail)->next = node;
				node->prev = *tail;
			}

			return node;
		}
	}
}


void remove_node(linked_list *node) {
	if (node != NULL) {
		if (node->prev != NULL) {
			node->prev->next = node->next;
		}

		if (node->next != NULL) {
			node->next->prev = node->prev;
		}

		free(node);
	}
}

linked_list *get_head(linked_list *node) {
	linked_list *head;
	for (head = node; head != NULL && head->prev != NULL; head = head->prev);
	return head;
}

linked_list *get_tail(linked_list *node) {
	linked_list *tail;
	for (tail = node; tail != NULL && tail->next != NULL; tail = tail->next);
	return tail;
}

int linked_list_size(linked_list *tail) {
	int i = 0;
	for (linked_list *node = tail; node != NULL; node = node->prev, ++i);
	return i;
}