SE250:lab-4:hals016
Lab 4
I started coding the length method by writing a for loop similiar to the one in the print_list method. The difference is that there needed to be a counter to keep track of all the elements.
int length(Cons* list) { int i; if (list->tail == 0) return 0; else { for (i = 0; list != nil; list = list->tail ) { i++; } return i; } }
When writing code to check the first element in the cons cell, I first made a condition that if the 'list->==nil' then 0 would be returned. Else 'list->head' would be returned.
element_t first(Cons* list) { if (list->tail == nil) return 0; else return list->head; }
Doing the second element was harder because it required a loop, I used the same loop and conditions for the third and fourth element but with the condition incremented slightly for each method.
element_t second(Cons* list) { int i; if (list->tail == nil) return 0; for (i = 0; i<1; list = list->tail ) { i++; } if (!(list->head==0)) return list->head; else return 0; }
The code for the nth element was straightforward because a template of element at second can be used with the for loop using the variable that indicats which element wants to be viewed.
element_t nth(int n,Cons* list) { int i; if (list->tail == nil && n>0 ) return 0; else { for (i = 0; i<(n-1); list = list->tail ) { i++; } } if (!(list->head==0)) return list->head; else return 0; }