为什么验证方法无法正常工作?

时间:2016-11-29 11:05:02

标签: c

我有一个方法可以在链接列表的开头插入:

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

在主要方法中,我使用上面的方法在开头插入一些元素:

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

在上面的主要方法中,我有方法验证实际数组是否等于预期的数组。但验证方法无法正常工作,因为我总是收到消息“不正确”,但列表是相同的。

你看到了什么问题吗?

验证方法:

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

1 个答案:

答案 0 :(得分:0)

试试这个:

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;
}
相关问题