2014-10-30 54 views
0

我想比較兩個鏈接列表。你能告訴我爲什麼我的代碼不起作用嗎?使用循環比較2個鏈接列表

如果兩個列表不同,則返回0;如果它們相同,則返回1。

int compare(struct Node *list1, struct Node *list2) 
{ 
    struct Node *node1 = list1; 
    struct Node *node2 = list2; 

    while ((node1) || (node2)) 
     if (node1->data != node2->data) 
      return 0; 
     else { 
      node1 = node1->next; 
      node2 = node2->next; 
     } 

    if ((node1 == NULL) && (node2 == NULL)) 
     return 1; 
    else 
     return 0; 
} 
+0

嘿,夥計能你提供完整的代碼。我無法單獨測試這種方法。 – harshitgupta 2014-10-30 21:01:39

+1

while條件應該使用'&&'而不是'||'。順便說一句,你過度使用括號! – ooga 2014-10-30 21:01:41

+0

@ooga也許,爲第一個while循環。 – 2014-10-30 21:05:23

回答

5

while條件應使用&&而不是||因爲你只希望它繼續如果兩個名單仍然有更多的節點。 (順便說一句,你是過度使用括號!)

int listEqual(struct Node *node1, struct Node *node2) { 

    while (node1 && node2) { 
     if (node1->data != node2->data) 
      return 0; 
     node1 = node1->next; 
     node2 = node2->next; 
    } 

    return node1 == NULL && node2 == NULL; 
} 

或者遞歸(但是這僅僅是合理的,如果你保證尾調用消除,如與gcc -O2):

int listEqual(struct Node *node1, struct Node *node2) { 
    if (node1 == NULL && node2 == NULL) 
     return 1; // If both are NULL, lists are equal 
    if (node1 == NULL || node2 == NULL) 
     return 0; // If one is NULL (but not both), lists are unequal 
    if (node1->data != node2->data) 
     return 0; 
    return listEqual(node1->next, node2->next); 
} 
+0

第一個答案很好。但是,它甚至考慮使用遞歸來遍歷鏈表。請不要在家裏試試這個,孩子。 – JS1 2014-10-30 22:51:17

+0

@ JS1好點!我在這裏假設消除尾巴。 (最近一直在使用lisp。) – ooga 2014-10-30 23:30:19

+0

我忘記提及我的鏈表實際上包含char *類型 – viethaihp291 2014-10-31 00:50:44