{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

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

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

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)); }

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

View Full Document
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]; head->next = array_to_list(a, j+1, n); return head; } } Calling the function: int numbers[] = {1, 2, 3, 4}; struct node *my_list;
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### 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
Ask a homework question - tutors are online