SE250:lab-4:dsan039

From Marks Wiki
Jump to navigation Jump to search

Overview

I've had issues with my computer so have been delayed in sorting out this lab work. Basically I spent the the bulk of the first hour learning how to use linked lists and create code necessary to work with them. Once i had done this i began to work through the tasks, and here is my results/code:

int length(Cons*)

This function navigates the cons list it and increments the iterator by 1 for each cons cell it passes through.

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

element t nth(int i,Cons*)

I figured if i can do this one i can probably do the task before it, so i gave it a shot. i knew it would require a loop, that it should stop if it hit a null (nill) pointer, but was then puzzled on what to do if that happened. the answer was pointed to me by someone else (don't bother) and so i just made the code very simple.

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

The reason why i can afford to not put a stop condition in is that the last element in the Cons list should hold (in its tail attribute) a Cons pointer to the cell NIL. (This pointer is called nil). If a number (i) is passed to this function which is higher than the number of elements in the list, the loop will hit the cons cell NIL, which has its own address stored in its tail attribute (meaning it points to itself). The head attribute of the NIL cell is 0, which means when the loop eventually ends, the value 0 will be returned. This could be dangerous if all the cells only stored int values and the user didn't realise they we accessing a cell that didn't really exist.

int equal(Cons* a, Cons* b)

int equal(Cons* a, Cons* b) {
    while (a != nil && b != nil) {
        if (a->head != b->head) {
            return 0;
        }
        a = a->tail;
        b = b->tail;
    }
    return 1;
}

I think the only important note here is the while loop condition, without checking for state nil, the loop would be infinite.


Cons* nappend(Cons* a, Cons* b)

This function was difficult for me so i moved onto the reverse function. Once i fully accepted that a cons list is built backwards (last element first), the code just followed. For nappend i studied jham's code to understand the concept behind it, was stuck for a bit not knowing why another local pointer to cons was made (which was equal to xs). the answer was that although the elements in the xs linked list needed to me read and accessed, the pointer (xs) itself needed to remain the same (and so could not be used to iterate through the list). Once this was clear i understood the code.