SE250:lab-4:hbar055

From Marks Wiki
Revision as of 05:19, 3 November 2008 by Mark (Sọ̀rọ̀ | contribs) (1 revision(s))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

This lab was obviously all about link lists. the main difficulty was the concept of the head and the tail of the link list.

Task One

int length(Cons* list) {
   int i;
   for (i = 0; list != nil; list = list->tail){
       i++;
   }
   return i;
}

This gives the length of the list passed into this function


Task Two

element_t first(Cons* first){
   return first->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 first function gives the element in the first position. Since this is a link list and not a normal array, it requires us to look at the tail of that particular list then point to the head to obtain the element for the following functions.


Task Three

element_t nth(int i, Cons* list){
    int j;
    for(j = 0; j <= i; j++){
        if(j == i){
          return list->head;
    }
    list = list->tail;
    return 0;
}

This is similar to the above task but it is not constrained by the limited number of lists to be checked


Task Four

int equal(Cons* xs ,Cons* ys){
    if(length(xs)==length(ys)){
         while(xs != nil){
            if(xs->head == ys->head){
                xs = xs->tail;
                ys = ys->tail;
                return 1;
            }else{
                return 0;
            }
        }
        return 1;
    }else{
        return 0;
    }
}

This compares the two link lists that have been passed into the function. Firstly it checks the length of the two lists then if that is met it then checks if the has the same elements in the same order. If both are met it then returns true.