SE250:lab-4:tlou006
Jump to navigation
Jump to search
Q1
Using the code
int length(Cons* list) { int length; for( length = 0 ; list != nil; list = list->tail ) { length++; } return length; }
loops through the list and returns the total length
Q2
Straight forward functions returning the first element in the list
element_t first(Cons* list) { if(list == nil) return 0; else return list->head; }
element_t fourth(Cons* list) { if(list == nil) return 0; else { list = list->tail; list = list->tail; list = list->tail; return list->head; } }
I found out that it was possible to list = list->tail->tail->tail etc..
Q3
Same as the previous task except the action was placed in a loop
element_t nth(int i, Cons* list) { int j; if(list == nil) return 0; else { for( j = 0; j < (i-1); j++ ) { list = list->tail; } return list->head; } }
Q4
This function loops through the list as long as the current values of both lists are the same, moving down the lists as soon as both lists are different or one list ends, then end the loop and return 0
int equal(Cons* list1 , Cons* list2) { while(list1->head == list2->head) { if((list1 == nil) && (list2 == nil)) { return 1; } else if((list1 != nil) && (list2 != nil)) { list1 = list1->tail; list2 = list2->tail; } } return 0; }
If both lists end at the same time and the values are the same then return 1
Q5
Had trouble thinking of code to loop through the list, so i used the example code instead lol
Cons* find(element_t i, Cons* list) { for( ; list != nil; list = list->tail ) { if(list->head == i) { return list; } } return nil; }