Return the length of a linked list 0 if the linked list is empty int

Return the length of a linked list 0 if the linked

This preview shows page 1 - 3 out of 5 pages.

Return the length of a linked list (0 if the linked list is empty). */ int length(intnode_t *head) { int count = 0; for (intnode_t * curr = head; curr != NULL; curr = curr->next) { count += 1; } return count; } /* Parameter head points to the first node in a linked list. Print the linked list, using the format: value1 -> value2 -> value3 -> ... -> last_value */ void print_list(intnode_t *head) {
Image of page 1
if (head == NULL) { printf("empty list"); return; } intnode_t *curr; /* The loop prints a every node in the linked list except the last one, using the format "value -> ", where "->" represents the link from each node to the following node. Notice that the loop condition is: curr->next != NULL and not: curr != NULL During the last iteration, the value in the second-last node is printed, then curr is updated to point to the last node. The condition curr->next != NULL now evaluates to false, so the loop exits, with curr pointing to the last node (which has not yet been printed.) */ for (curr = head; curr->next != NULL; curr = curr->next) { printf("%d -> ", curr->value); } /* Print the last node. */ printf("%d", curr->value); } /***************************************************************** * Solutions to Lab 8 *****************************************************************/ // Exercise 1 /* Parameter head points to the first node in a linked list, or is * NULL if the list is empty. * * Count the number of nodes in the linked list that contain an integer * equal to target, and return that count. * * Return 0 if the linked list is empty.
Image of page 2
Image of page 3

You've reached the end of your free preview.

Want to read all 5 pages?

  • Spring '12
  • schram
  • Pointer, #include, new IntNode

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture