验证方法为何无法正常工作?

问题描述:

我有在开始一个链表的插入方法:验证方法为何无法正常工作?

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

在main方法林插入在一些元素开始使用上述方法:

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

你什么输出?你期望什么输出。请阅读以下内容:[MCVE] –

+0

您的验证方法在正确时返回0,在错误时返回其他值。你的if语句检查返回 – Fefux

+0

'return -1;'表示'返回true;' – BLUEPIXY

试试这个:

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