SE250:lab-4:stsa027
Writing the int length(Cons*) function:
I reused the code already provided in the for loop in LL.c, and simply added an extra variable. I initially called the variable length, same as the function name and was told this was not a good idea. So, it was changed to len.
I then copied and paseted the test code provided by the lecturer into the main function, and it was a success.
Code used:
int length(Cons* list) { int len = 0; for( ; list != nil ; list = list-> tail) len++; return len; }
Writing the element_t first to fourth (Cons*) function:
Even for the first one, I was slightly confused about what to do. The lecturer gave me the advice of NOT using a for loop as I was attempting, since all you have to do was return the head of the first element of the list. He also said that since nil is a valid cons cell in inself, with a head of 0 and a tail pointing to another nil cons cell, the following
if (list == nil) //redundant return 0; //redundant
is not really required.
For writing the second function, I first tried this:
element_t second(Cons* list) { if (list == nil)
return 0;
return element_t a; for( ; list != nil ; list = list->tail)
a = list->head;
return a;
which worked, but is a rather complicated way of doing things, as I was told by the tutor. Instead, I was advised to use this:
return list->tail->head;
A similar thing was done with returning third and forth element_t.
Writing the element_t nth(int i, Cons*) function:
Writing the Cons* find(element_t, Cons*) function:
Writing the Cons* copy_list(Cons* xs, Cons* xs) function:
Cons* copy_list (Cons* xs){ Cons* copy = nil; Cons* xs_orig = xs; int j = 0; int i = (length(xs_orig))-1; while(length(copy)<length(xs_orig)){ while(j!=i){ j++; xs = xs->tail; } copy = cons((xs->head), copy); i--; xs = xs_orig; j=0; } return copy; }
Writing the Cons* nappend(Cons* xs, Cons* xs) function:
Cons* nappend(Cons* xs, Cons* ys){ Cons* both = xs; if (xs == nil) return ys; while(both->tail!=nil){ both = both->tail; } both->tail = ys; return xs; }
Writing the Cons* reverse(Cons* xs, Cons* xs) function:
Cons* reverse(Cons* xs){ Cons* rev = nil; for (; xs!=nil; xs = xs->tail){ rev = cons((xs->head), rev); //points rev to a new cons cell using the next xs->head, and original address of rev } return rev; }
Writing the Cons* nreverse(Cons* xs, Cons* xs) function:
Cons* nreverse(Cons* xs){ int i = length(xs); Cons* copy = xs; Cons* copyi = xs; while(xs->tail!=nil) xs = xs->tail; //makes xs point to the last element of the array list which has a tail that points to null while (copy->tail!=nil){ copyi = copy; //copyi is arranged to be pointing to the element before copy copy = copy->tail; //copy points to the last element (which has a tail that points to null) if(copy->tail==nil){ copy->tail = copyi; copyi->tail = nil; break; } } return xs; }