SE250:lab-4:vpup001
Jump to navigation
Jump to search
Link lists
- The function to return the number of elements in the list.
int length(Cons* list) { int i = 0; for ( ; list!=nil; list=list->tail) { i++; } return i; }
- The functions that returns the elements in the named position (i.e first, second, third, fourth) and returns 0 if no such element exists.
element_t first(Cons* list) { return list->head; }
element_t second(Cons* list) { return list->tail->head; }
element_t third(Cons* list) { return list->tail->tail->head; }
element_t fourth(Cons* list) { return list->tail->tail->tail->head; }
- The function that returns the i'th element in a list or 0 if no such element exists (generalizing the above functions)
element_t nth(int i, Cons* list) { while(i!=0) { list = list->tail; i--; } return list->head; }
The while loop is used to go through every element in the list. If i is not equal to 0 it checks the next element and it does that until i is 0 and returns list->head.
- The function that returns true if both lists have exactly the same elements in the same order, false otherwise.
int equal(Cons* list1, Cons* list2) { while (list1 != nil && list2 != nil) { if (list1->head == list2->head) { list1 = list1->tail; list2 = list2->tail; return 1; } else { return 0; } } }