2016-01-28 17 views
2

使用單鏈表,我返回一個包含元素集合C只存在於集合A,而不是在組B.爲什麼我的方法打印列表的最後一個元素時,它不應該?

A套裝包含:30,20,項目2,物品1,10,26

B組含有:88,項目3,項目30,項目4,項目26,項目100

A.complement(B);應該輸出{20 item2 item1 10},

但我得到{20 item2 item1 10 26}和'26'不應該在集合中。 即使繪製出列表圖,我仍然無法弄清楚什麼是錯誤的。

public boolean otherContain(Object obj) { // returns true if object is 
              // inside singly linked list 
    Node cur = head.next; 

    while (cur != null) { 
     if (cur.object.equals(obj)) 
      return true; 
     else 
      cur = cur.next; 
    } 

    return false; 
} 


public Set complement(Set a) {// return set containing elements only in A 
           // not shared with B 
    Set c = new Set(); 
    Node curC = c.head; 
    Node cur = head.next; 

    while (cur != null) { 

     if (a.otherContain(cur.object)) { 
      cur = cur.next; 
     } else if (!a.otherContain(cur.object)) { 
      curC.next = cur; 
      curC = curC.next; 
      cur = cur.next; 
     } 
    } 
    return c; 
} 

*************更新工作方法************************

public Set complement(Set a) {// return set containing elements only in A 
           // not shared with B 
    Set c = new Set(); 
    Node newNode = c.head; 
    Node cur = head.next; 

    while (cur != null) { 

     if (a.otherContain(cur.object)) { 
      cur = cur.next; 
     } else if (!a.otherContain(cur.object)) { 
      newNode.next = new Node(cur.object, newNode.next); 
      cur = cur.next; 
     } 
    } 
    return c; 
} 
+0

單個鏈接的集合,它必須是作業。我建議你使用你的調試器來幫助你調試你的代碼。 –

回答

1

您的問題是您正在重用輸出集中的輸入集的節點,因此您添加到輸出集-10的最終節點仍然是指輸入集的最後一個節點 - 26。您應該爲輸出集創建新的節點。

public Set complement(Set a) { 
    Set c = new Set(); 
    Node curC = c.head; 
    Node cur = head.next; 

    while (cur != null) { 
     if (!a.otherContain(cur.object)) { 
      Node newNode = new Node(); 
      newNode.object = cur.object; 
      newNode.next = null; 
      curC.next = newNode; 
      curC = curC.next; 
     } 
     cur = cur.next; 
    } 
    return c; 
} 
+0

謝謝,在您發佈代碼之前,請遵循您的建議並且工作正常! – asdf

+0

@hobbes對你有好處!自己編寫代碼總是更好。 – Eran

相關問題