SE250:lab-4:srag014

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

This Lab is all to do with linked lists, were provided with starter code and then told to implent different functions.

Task1

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

I tested the function the function by inserting 4 linked lists and it returned with a value of 4 which in this case is the desired output.

Task 2

Second task pretty much involved writing three functions namely element t first(Cons*), element t second(Cons*),element t third(Cons*), and element t fourth(Cons*) returning the element.

element_t first(Cons* list) {
if(list == nil) {
return 0;
}
return list->head;
}
element_t second(Cons* list) {
if(list == nil) {
return 0;
}
return list->tail->head;
}
element_t third(Cons* list) {
if(list == nil) {
return 0;
}
return list->tail->tail->head;
} 
element_t fourth(Cons* list) {
if(list == nil) {
return 0;
}
return list->tail->tail->head;
}

Task 3

This task was pretty much similar to the previous one except it is for the nth loop. I got really confused with the for loop and how to implent it with the linked list but my neighbour helped me out.

element_t nth(int i, Cons* list) {
int j = 0;
Cons *find1 = list;
if(list == nil) {
return 0;
}
for(j; j < i; j++) {
if(list->tail == nil) {
break;
}
find1 = find1->tail;
}
return find1->head;
}

Task 4

We had to wirte a function that returns true if both lists have exactly the same elements in the same order, if it not it had to return false.

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

Task 5

Task 5 involved writing a function to search for an element in the list and return the Cons cell that contains this value, or the empty list if it does not occur in the list. This is where i got upto when the time was up. Ill finish this lab later on in the week as theres a bit too many tests/assignments on at the moment