



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




struct node { char data ; struct node * next ; }
struct node * cons ( char first , struct node * rest ) { struct node * linked_list ; linked_list = malloc ( sizeof ( struct node )); linked_list - > data = first ; linked_list - > next = rest ; }
char first ( struct node * linked_list ) { return linked_list - > data ; }
struct node * rest ( struct node linked_list ) { return old_list - > next ; }
struct node * node_ptr = linked_list ; while (( node_ptr = node_ptr - > next ) != NULL ) { sum += node_ptr - > data }
int sum ( struct node * linked_list ) { return linked_list - > data + sum ( linked_list - > next ); }
Comparison to Dynamic Arrays
An Example Removal of Matching Nodes from Singly- and
Doubly-Linked Lists
struct node * p = ll - > first ;
// iterate over the nodes while ( p != NULL ) { // if the node matches x , delete the node if (p - > data == x ) { struct node * n = p ; p = p - > next ;
// connect predecessor to its new successor if (n - > prev != NULL ) n - > prev - > next = n - > next ; else
ll - > first = n - > next ;
// connect successor to its new predecessor if (n - > next != NULL ) n - > next - > prev = n - > prev ; else ll - > last = n - > prev ;
// delete the node free ( n ); } else { p = p - > next ; } }
struct node *p , * n ;
while ( ll - > first != NULL && ll - > first - > data == x ) { n = ll - > first ; ll - > first = n - > next ; free ( n ); }
p = ll - > first ; // iterate over the nodes p - > next , and find those which match x while ( p != NULL && p - > next != NULL ) { struct node * n = p - > next ;
if (n - > data == x ) { // connect the predecessor to its new successor p - > next = n - > next ;
// update the last link , if necessary if (n - > next == NULL ) ll - > last = p ;
// deallocate the memory for the node free ( n ); } else { p = p - > next ; } }