SE250:lab-4:jhor053

From Marks Wiki
Jump to navigation Jump to search

Lab 4

Task 1

Here is my code:

int length(Cons* list){
	int length = 0; 
	for( ; list != nil; list = list->tail ) {    
		length++;
	}  
	//printf("\nLength of list = %d\n", length);
	return length;
}

A simple for loop to go over the array with an int being iterated for each part it finds and increases then reports the size back.

Results:

Length of list = 3

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

Which took me ages to realise but since it will keep on going to its tail till the nth required place (ie since its next value is stored just follow that till at required head)

Results:

First = 1
Second = 2
Third = 3
4th value ie test for no value= 0

Task 4

My code:

element_t nth(int i,Cons* list){
	int length = 1;
	list->head;

	for( ; list != nil && length < i; list = list->tail ) {    
		length++;
	}

	return list->head;
}

This just iterates over till it finds the nth position.

It also self corrects if it is empty as shown by my results..

With a for loop in main to try different positions of n:

Test of nth value
1
2
3
0


I arrived late and too busy tonight so will ahve to complete the lab on thursday