diff options
| author | mo khan <mo.khan@gmail.com> | 2020-07-05 14:37:54 -0600 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2020-07-05 14:37:54 -0600 |
| commit | 50aed9bff66f28962edae97be3be49a37ba8f523 (patch) | |
| tree | 485d2b9ad4f66a218cec643fc1d8d073206425a0 /src/01 | |
| parent | 0d0a5c470fe1541193c8248adfedc535cecd3fab (diff) | |
Add each iterator
Diffstat (limited to 'src/01')
| -rw-r--r-- | src/01/02b/doubly_linked_list.c | 25 | ||||
| -rw-r--r-- | src/01/02b/doubly_linked_list.h | 1 |
2 files changed, 18 insertions, 8 deletions
diff --git a/src/01/02b/doubly_linked_list.c b/src/01/02b/doubly_linked_list.c index 4a46fcf..86fb1ce 100644 --- a/src/01/02b/doubly_linked_list.c +++ b/src/01/02b/doubly_linked_list.c @@ -147,6 +147,22 @@ static void print(Node *node) { printf("(nil<%d>%d)", node->data, node->next->data); else printf("(%d<%d>nil)", node->prev->data, node->data); + printf(" "); +} + +/** + * Iterates through each node in a linked list. + * + * @param self The node to start iterating from. + * @param block The callback function to invoke on each node. + */ +void each(Node *self, Visitor block) { + Node *tmp = self; + + while (tmp) { + block(tmp); + tmp = tmp->next; + } } /** @@ -155,14 +171,7 @@ static void print(Node *node) { * @param node The head of the linked list */ void inspect(Node *node) { - if (!node) - return; - printf("[ "); - while (node) { - print(node); - printf(" "); - node = node->next; - } + each(node, &print); printf("]\n"); } diff --git a/src/01/02b/doubly_linked_list.h b/src/01/02b/doubly_linked_list.h index 5a44ae3..abd053e 100644 --- a/src/01/02b/doubly_linked_list.h +++ b/src/01/02b/doubly_linked_list.h @@ -5,6 +5,7 @@ struct node { }; typedef struct node Node; +typedef void (Visitor)(Node *); Node *initialize(int data); Node *add(Node *head, int data); |
