lists2 - Look up an item in the list pointed by head...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Programming Exercises Counting the nodes in a List Recursive version: int count (struct node * head) { if (head==NULL) return 0; else return(1 + count(head->next)); } Iterative version: int count(struct node *head) { struct node * p; int c = 0; p = head; while (p != NULL){ c = c + 1; p = p->next; } return c; } 2 Look up an item in the list pointed by head /* Given the item and the pointer to the head of the list, the function returns NULL if the item is not found; or returns a pointer to the node which matches the item */ struct node * lookup(int item, struct node *head) { if (head == NULL) return NULL; else if (item == head->data) return head; else return(lookup(item, head->next)); }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
3 Creating a List Recursive version: // Copies the contents of an array into a // dynamically growing list. struct node *array_to_list(int a[], int j, int n) { struct node *head; if (j >= n) //base case return NULL; else { head = (struct node *) malloc(sizeof(struct node)); head->data = a[j];
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This document was uploaded on 06/12/2011.

Page1 / 5

lists2 - Look up an item in the list pointed by head...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online