Create a function (listyCmp) using the unit_test function below. WHen done corre
ID: 3723822 • Letter: C
Question
Create a function (listyCmp) using the unit_test function below. WHen done correctly, the output should produce "Hooray" as defined in the unit_test function
int unit_test(int argc, char **argv)
{
int success = 1;
ListyString *listy1, *listy2;
// Manually create a listy string. This is awful.
listy1 = malloc(sizeof(ListyString));
listy1->head = malloc(sizeof(ListyNode));
listy1->head->next = malloc(sizeof(ListyNode));
listy1->head->next->next = malloc(sizeof(ListyNode));
listy1->head->next->next->next = NULL;
listy1->head->data = 'c';
listy1->head->next->data = 'a';
listy1->head->next->next->data = 't';
listy1->length = 3;
// Manually create another listy string. This is awful.
listy2 = malloc(sizeof(ListyString));
listy2->head = malloc(sizeof(ListyNode));
listy2->head->next = malloc(sizeof(ListyNode));
listy2->head->next->next = malloc(sizeof(ListyNode));
listy2->head->next->next->next = NULL;
listy2->head->data = 'c';
listy2->head->next->data = 'a';
listy2->head->next->next->data = 'n';
listy2->length = 3;
if (listyCmp(listy1, listy2) == 0)
success = 0;
printf("%s ", success ? "Hooray!" : "fail whale :(");
return 0;
}
Description: Compare the two ListyStrings. Return 0 (zero) if they represent equivalent strings. Otherwise, return any non-zero integer of your choosing. Note that the following are not considered equivalent: (1) a NULL ListyString pointer and (2) a non-NULL ListyString pointer in which the head member is set to NULL (or, equivalently, the length member is set to zero). For the purposes of this particular function, (2) represents an empty string, but (1) does not. Two NULL pointers are considered equivalent, and two empty strings are considered equivalent, but a NULL pointer is not equivalent to an empty string.
Runtime Requirement: The runtime of this function must be no worse than O(n+m), where n is the length of listy1 and m is the length of listy2.
Returns: 0 (zero) if the ListyStrings represent equivalent strings; otherwise, return any integer other than zero.
Explanation / Answer
int listyCmp(ListyString *listy1, ListyString *listy2){
ListyString temp = listy1->head;
ListyString temp1 = listy2->head;
while( temp != NULL && temp1!=NULL) {
if(temp->data != temp1->data )
return 0;
temp = temp->next;
temp1 = temp1->next;
}
if(temp==NULL && temp1==NULL)
return 1;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.