Pages

Wednesday 11 July 2012

Get Nth element from a linked list


int GetNth(struct node* head, int index) {
struct node* current = head;
int count = 0;
while (current != NULL) {
if (count == index) return(current->data);
count++;
current = current->next;
}
assert(0); // if we get to this line, the caller was asking
// for a non-existent element so we assert fail.
}


No comments:

Post a Comment