length
int length(Cons* list){
int length = 0;
for( ; list !=nil; list = list->tail) {
length++;
}
return length;
}
- Pretty straight forward, goes through each cells in the list and increase the length by 1 each time.
element_t first
element_t first(Cons* list){
return list->head;
}
- Again, straight forward, just returning the first cell's head.
element_t second
element_t second(Cons* list){
return list->tail->head;
}
- I wrote an if statement at first returning nil if the list is only 1 cell long.
- However, realized the following
static Cons NIL = { 0, &NIL };
Cons* nil = &NIL;
- After realizing a nil cell was already set up, which is always pointing to itself, the code doesn't need an if statement as the list will continue to go through the NIL cell until the end.
element_t third and fourth
element_t third(Cons* list){
return list->tail->tail->head;
}
element_t fourth(Cons* list){
return list->tail->tail->tail->head;
}
- Pretty dull as it just goes through the NIL cell over and over and over again...
element_t nth
element_t nth(int i, Cons* list){
int n;
if (i <= 0) {
return 0;
}
for ( n = 0; n < i; n++) {
list = list->tail;
}
return list->head;
}
- Straight forward, goes through the list until it reaches the cell told and returns the head of it.
equal
int equal(Cons* listA, Cons* listB){
for( ; listA != nil; listA = listA->tail){
if (listA->head != listB->head){
return 0;
}
listB = listB->tail;
}
if (listA->tail == listB->tail) {
return 1;
}
return 0;
}
- Had some problem trying to figure out if they both have the same head, however 1 list is longer than the other 1.
- Problem solved by checking the tail of both list for equality, because if both are the same length and contains the same elements, both should have nil as the tail.
find