Created
February 1, 2016 20:24
-
-
Save maksspace/0cb5ce699d52fccb01e1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define LIST_NODE(type) \ | |
struct { \ | |
type data; \ | |
size_t next; \ | |
size_t prev; \ | |
} | |
#define LIST_NODE_LINK_INIT(name) {(name)->next = (name)->prev = 0;} | |
#define LIST_NODE_NEXT(node_ptr) ((typeof(node_ptr))((node_ptr)->next)) | |
#define LIST_NODE_PREV(node_ptr) ((typeof(node_ptr))((node_ptr)->prev)) | |
#define LIST_NODE_GET(type, node_ptr) ((LIST_NODE(type)*)(node_ptr)) | |
#define LIST_INSERT(new_node, prev_node, next_node) \ | |
if((next_node) == 0) { \ | |
(prev_node)->next = (size_t)(new_node); \ | |
(new_node)->prev = (size_t)(prev_node); \ | |
(new_node)->next = 0; \ | |
} \ | |
else { \ | |
(next_node)->prev = (size_t)(new_node); \ | |
(new_node)->next = (size_t)(next_node); \ | |
(new_node)->prev = (size_t)(prev_node); \ | |
(prev_node)->next = (size_t)(new_node); \ | |
} | |
#define LIST_PREPEND(node, head) \ | |
{(head)->prev = (size_t)(node); \ | |
(node)->next = (size_t)(head); \ | |
(node)->prev = 0; \ | |
(head) = (node);} | |
#define LIST_ITER(ptr) (size_t)(ptr) | |
#define LIST_ITER_DOWN(iter_name, head_ptr) (iter_name) = (size_t)LIST_NODE_NEXT((typeof(head_ptr))iter_name) | |
#define LIST_ITER_UP(iter_name, tail_ptr) (iter_name) = (size_t)LIST_NODE_PREV((typeof(tail_ptr))iter_name) | |
#define LIST_NODE_DELETE(from, to) \ | |
{(from)->next = (size_t)(to); \ | |
(to)->prev = (size_t)(foo);} | |
#define LIST_DELETE_STATIC(type, head, free_data) \ | |
{size_t current_node = (size_t)(head); \ | |
size_t next_node = 0;\ | |
while(current_node != 0) {\ | |
next_node = LIST_NODE_GET(LIST_NODE(type), current_node)->next;\ | |
free_data((void*)current_node);\ | |
current_node = next_node;\ | |
}} | |
// ---------------------------- | |
int main(int argc, char *argv[]) | |
{ | |
LIST_NODE(int)* head = malloc(sizeof(LIST_NODE(int))); | |
LIST_NODE_LINK_INIT(head); | |
head->data = 0; | |
LIST_NODE(int)* tail = head; | |
for(int i = 1; i < 1000; i++) { | |
LIST_NODE(int)* tmp = malloc(sizeof(LIST_NODE(int))); | |
tmp->data = i; | |
LIST_PREPEND(tmp, head); | |
} | |
for(size_t current = LIST_ITER(tail); current != 0; LIST_ITER_UP(current, tail)) | |
printf("%d\n", LIST_NODE_GET(int, current)->data); | |
LIST_DELETE_STATIC(int, head, free); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment