SE250:lab-4:rbha033

From Marks Wiki
Jump to navigation Jump to search

Lab 4

Task 1

So here's my code for the length(Cons* list) function:

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

After writing this code, I was told that I needed to copy the "test_LL()" function above the "main()" function. The compiler gives an error if the function is below the "main()" function. I was also given a tip that I should exclude the test cases in the "test_LL()" function which are not yet applicable. To do this we use "#if 0" before the first line of code you want to ignore and "#endif" after the last line of code that needs to be ignored. Anything (block of code) between the two statements will be ignored.

Task 2

Here's my code for task 2:

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;
}

Now we dont need to have a check as any empty cell will have head = 0. If there's something stored, it'll show up, otherwise it'll show 0.

Task 3

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

Task 4

Task 5

Task 6

Task 7

Task 8

Task 9

Task 10