Jax Jax - 11 days ago 7
C Question

Why the verify method is not working properly?

I have a method to insert at the begin of a linked list:

void insertBegin(int value)
{
struct node *var;

var=(struct node *)malloc(sizeof (struct node));
var->data=value;
if(head==NULL)
{
head=var;
head->next=NULL;
}
else
{
var->next=head;
head=var;
}
}


In the main method Im inserting some elements at the begin using the method above:

int main{
int actual[] = {50, 70, 80, 100, 77, 200, 44, 70, 6, 0};
int expected[] = {0, 6, 70, 44, 200, 77, 100, 80, 70, 50};

for(i=0; i<listsize; i++){
insertBegin(actual[i]);
}

if(verify(expected))
printf("correct");
else
printf("incorrect");
return 0;
}


And in the main method above i have the method verify to see if the actual array is equal to the expected array. But the verify method is not working properly because Im always getting the message "incorrect", but the lists are the same.

Do you see what is wrong?

verify method:

int verify(int expected[]) {
struct node *temp;
int i;

if (head == NULL)
return -1;

if (expected[0] != head->data)
return -1;
i = 1;
temp = head->next;

for (i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (temp->data == expected[i])
return true;
else
return false;
}
}
return 0;
}

Answer

try this:

bool verify(int expected[]) {
    struct node *temp = head;
    int i = 0;

    if(temp == NULL)
        return false;

    while(temp){
        if(expected[i++] != temp->data)//if(i == listsize || expected[i++] != temp->data)
            return false;
        temp = temp->next;
    }
    return true;
}