Linked Structures
Linked Structure Tradeoffs
Buildng a Linked List in C
Adding to a List
Traversing a List
Organizing our List Code
Reusable Traversal Implementation
}
* Here’s how to use the traversal function.
traverse( myVisitor );->This gives the address of the
myVisitor() function.
use static most of the time to not pollute global namespace
Organizing Our List Code(New Way)
Faking Object Orientation
Freeing Lists
Don’t do this!
* Eventually, we have to free the memory for
our linked list
* Here’s a bad way to do it:
for ( Node *n = head; n; n = n->next )
free( n );
(n->next in for loop )-> didn’t you just free that node?
* This tries to use a node, right after we free it.
Correct Way!
while ( head ) {
Node *next = head->next;
free( head );
head = next;
}
Removing Node
Getting Creative
Pointer to Node
Pointer to a Pointer to a Node
Traversing via Pointer to Pointers
Removing Nodes(Simplified)
Removing Nodes(Simplified Code)
bool removeValue( List list, int val )
{
Node **target = &list->head;
while ( target && (target)->value != val )
target = &(target)->next;
if ( *target ) {
Node *n = *target;
target = (target)->next;
free( n );
return true;
}
return false;
}
Binary Search Trees
Building a BST
Finding a Value
bool containsKey( Tree *tree, int val )
{
Node *n = tree->root;
while ( n ) {
if ( n->key == val )
return true;
if ( val < n->key )
n = n->left;
else
n = n->right;
}
return false;
}
Tree Traversal(Code)
Generic Tree Traversal