# LinkedLists2 - Programming Exercises Counting the nodes in a List Recursive version int count(struct node head cfw if(head=NULL return 0 else

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

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

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

View Full Document
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)); } 2
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,

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

View Full Document
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 / 10

LinkedLists2 - Programming Exercises Counting the nodes in a List Recursive version int count(struct node head cfw if(head=NULL return 0 else

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

View Full Document
Ask a homework question - tutors are online