Skip to content

Commit 38e6e3c

Browse files
committed
Added linked list skeleton.
1 parent a94e365 commit 38e6e3c

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

datastructures/linkedlist.h

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <stddef.h>
2+
3+
struct list_node_t {
4+
struct list_node_t *next;
5+
};
6+
7+
typedef struct list_node_t *list_node_p;
8+
typedef struct list_node_t list_node_t;
9+
10+
int list_insert(list_node_p *list, list_node_p node)
11+
{
12+
node->next = *list;
13+
*list = node;
14+
15+
return 0;
16+
}
17+
18+
19+
int list_remove(list_node_p *list, list_node_p node)
20+
{
21+
list_node_p *indirect_next = list;
22+
23+
while(*indirect_next && *indirect_next != node) {
24+
indirect_next = &(*indirect_next)->next;
25+
}
26+
27+
if(*indirect_next == node) {
28+
*indirect_next = node->next;
29+
}
30+
31+
return 0;
32+
}
33+
34+
#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))

datastructures/linkedlist_test.c

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <stdio.h>
2+
3+
#include "linkedlist.h"
4+
5+
struct test_data {
6+
int i;
7+
list_node_t list;
8+
};
9+
10+
int main()
11+
{
12+
list_node_p list = NULL;
13+
struct test_data nodes[3] = { {0,NULL}, {1,NULL}, {2,NULL}};
14+
15+
list_insert(&list,&(nodes[2].list));
16+
list_insert(&list,&(nodes[0].list));
17+
list_insert(&list,&(nodes[1].list));
18+
19+
for(list_node_p node_p = list; node_p; node_p = node_p->next) {
20+
struct test_data *data_p = container_of(node_p, struct test_data, list);
21+
printf("Node data %d\n",data_p->i);
22+
}
23+
24+
return 0;
25+
}

0 commit comments

Comments
 (0)