SE250:lab-4:sdal039
Running the assert checks on the functions below shows that they all work as expected.
int length(Cons* list) { len = 0; for( ; list != nil ; list = list->tail, len++ ); return len; }
element_t first(Cons* list) { int i = 0; for( ; list != nil && i < 0 ; list = list->tail, i++ ); return list->head; }
element_t second(Cons* list) { int i = 0; for( ; list != nil && i < 1 ; list = list->tail, i++ ); return list->head; }
element_t third(Cons* list) { int i = 0; for( ; list != nil && i < 2; list = list->tail, i++ ); return list->head; }
element_t fourth(Cons* list) { int i = 0; for( ; list != nil && i < 3; list = list->tail, i++ ); return list->head; }
element_t nth(int j, Cons* list) { int i = 0; for( ; list != nil && i < j ; list = list->tail, i++ ); return list->head; }
int equal(Cons* l1, Cons* l2) { if ((l1 != nil && l2 == nil) || (l1 == nil && l2 != nil)) return 0; for( ; l1 != nil && l2 != nil ; l1 = l1->tail, l2 = l2->tail ) { if (l1->head != l2->head) return 0; } //must be equal return 1; }
Cons* find(element_t elt, Cons* list) { for( ; list != nil && list->head != elt ; list = list->tail); return list; }
Cons* reverse(Cons* list) { Cons* list_copy = nil; for( ; list != nil ; list = list->tail) list_copy = cons(list->head, list_copy); return list_copy; }
One particularly hard part of this lab was the copy_list function. After getting some strange results, it turned out that with only a few changes it could be turned into the "reverse" function and so copy_list was left alone.
Cons* nappend(Cons* list1, Cons* list2) { for( ; ; list1 = list1->tail) { if ((list1->tail == nil) | (list1 == nil)) list1->tail = list2; return list1; } }
This code nearly works, giving the output
List[] List[] List[10] List[10,20]
where the expected output is
List[] List[10] List[10] List[10,20]