Created
December 17, 2014 02:04
-
-
Save dmcaulay/ce729c4725d7530d97d1 to your computer and use it in GitHub Desktop.
an example using the linux linked list data structure
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 person who has siblings and children | |
struct person { | |
int age; | |
struct list_head siblings; | |
struct list_head children; | |
} | |
// declare a father | |
struct person father = { | |
.age = 32, | |
.sibling = LIST_HEAD_INIT(child.sibling), | |
.children = LIST_HEAD_INIT(father.children), | |
}; | |
// declare a child | |
struct person son = { | |
.age = 5, | |
.sibling = LIST_HEAD_INIT(child.sibling), | |
.children = LIST_HEAD_INIT(child.children), | |
}; | |
// add a child | |
list_add(&son->sibling, &parent->children); | |
// iterate | |
struct list_head *current; | |
struct person *child; | |
// macro for each | |
list_for_each(current, father.children) { | |
child = container_of(current, struct person, children); | |
// process the child | |
} | |
// without container_of dependency | |
list_for_each_entry(child, father.children, children) { | |
// process the child | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment