aboutsummaryrefslogtreecommitdiff
path: root/llist.h
blob: 340ab0f52d00c15d76a8a504c5d5b410ae7167e5 (plain) (blame)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct node{
	void *data;
	struct node *next;
} node;

typedef struct llist{
	char *name;
	node *head;
} llist;

node *Node(void *data, size_t size){
	node *nnode = malloc(sizeof(node));
	nnode->data = malloc(size);
	memmove(nnode->data, data, size);
	nnode->next = NULL;
	return nnode;
}

llist Llist(char *name, node *head){
	llist nllist = {.name = name, .head = head};
	return nllist;
}

void append(llist l, node *n){
	if(l.head != NULL){
		node *temp = l.head;
		while(temp->next != NULL)
			temp = temp-> next;
		temp->next = n;
	}else{
		l.head = n;
	}
}

void insert(llist *l, node *n){
	if(l->head != NULL){
		node *temp = l->head;
		n->next = temp;
	}
	l->head = n;
}

void insertPos(llist *l, node *n, size_t pos){
	int i = 0;
	if(l->head != NULL){
		if(pos == 0){
			insert(l, n);
			return;
		}
		node *t = NULL;
		node *tnext = l->head;
		for(i = 0; i < pos && tnext != NULL; ++i){
			t = tnext;
			tnext = t->next;
		}
		if(tnext == NULL && i != pos){
			goto poserr;
		}
		t->next = n;
		n->next = tnext;
	}
poserr:
	fprintf(stderr, "Couldn't insert at desired position. "
			"Inserting at position %d", i);
}