2016-11-29 52 views
-2

我有在開始一個鏈表的插入方法:驗證方法爲何無法正常工作?

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

回答

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