SE250:lab-4:mabd065

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

Introduction

Task 1

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

A straight forward task.

Task 2

Started with this code:

element_t first( Cons* list ) {
    int first_element;
    if (list != nil) {
 	first_element = list->head;
	return first_element;
    } else {
	return 0;
    }
}

This code worked fine. But the replaced it with a simpler one:

element_t first( Cons* list ) {
    return list->head;
}

And then the following tasks for returning a value:

element_t second( Cons* list ) {
    int i = 0, j = 1;
    while ( (i < j) && (list != nil) ) {
	list = list->tail;
	i++;
    }
    return list->head;
}
element_t third( Cons* list ) {
    int i = 0, j = 2;
    while ( (i < j) && (list != nil) ) {
	list = list->tail;
	i++;
    }
    return list->head;
}
element_t fourth( Cons* list ) {
    int i = 0, j = 3;
    while ( (i < j) && (list != nil) ) {
	list = list->tail;
	i++;
    }
    return list->head;
}
element_t nth(int k, Cons* list ) {
    int i = 0, j = (k);
    while ( (i < j) && (list != nil) ) {
	list = list->tail;
	i++;
    }
    return list->head;
}

Task 3

The equal function. It took me a while to think about it:

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


Task 4

The find one was way simpler than i thought:

Cons* find( element_t value, Cons* list ) {
    while ( list != nil ) {
	if (list->head == value) {
	    return list;
	}
	list = list->tail;
    }
   return list; 
}


I have tired my own test cases. But when i used the lecturer ones, i found some minor errors and fixed them.