[英]Implementing methods from a class to a interface as a linked list
我有這些以下方法,我想在名為 LinkedBag 的 class 中實現它
void replace(T oldEntry, T newEntry){}
boolean isDuplicated(T anEntry){}
void doubleBag(){}
void replace(T oldEntry,T newEntry)
將任何等於oldEntry
的條目替換為新條目newEntry
。 例如,假設在這個包 {A,B,C,A} 上調用了replace(A,D)
。 結果包應該是{D,B,C,D}
anEntry
在包中出現多次,則 boolean 返回 true,否則返回 false。 例如,在第 1 部分中對結果包調用isDuplicated(B)
應該返回 false,但isDuplicated(D)
應該返回 true。void doubleBag()
將出現在包中的每個條目的副本添加到包中。 例如,在第 1 部分中對結果包調用 doubleBag() 應將包內容更改為{4'D, 2'B, 2'C}
。現在到目前為止,我想獲取節點的頻率並檢查節點是否重復,例如:
public boolean isDuplicated(T anEntry){
Node currentNode =firstNode;
int counter=0;
while ((counter <numberOfEntries)&&(currentNode!=null))
if(anEntry.equals(currentNode)){
return true;
}
return false;
}
對於replace
方法,我嘗試將值分配給另一個變量,然后刪除它們,然后再次重新分配它們,但我認為這是不對的
T entry=null;
T entry1 = null;
oldEntry=entry;
newEntry=entry1;
remove(oldEntry);
entry=newEntry;
entry1=oldEntry;
add(oldEntry);
add(newEntry);
System.out.println( oldEntry+" , "+newEntry );
}
至於雙包我還是不知道怎么弄。
請原諒我的編程不好我正在學習 java 新的,並且仍在學習基礎知識。
讓我們簡單地看一下您的replace
方法:
T entry = null;
T entry1 = null;
// entry and entry1 are both null
oldEntry = entry;
newEntry = entry1;
// entry, entry1, oldEntry and newEntry are all null.
remove(oldEntry); // remove null
entry = newEntry; // overwriting null with null
entry1 = oldEntry; // same as previous statement
add(oldEntry); // add null
add(newEntry); // add null again
// print "null , null"
System.out.println(oldEntry + " , " + newEntry);
目前尚不清楚您要做什么,但至少這里的東西只是一堆什么都沒有。 你可能想要的更像是這樣的:
// assuming oldEntry and newEntry are set somewhere and are correct,
// and that remove and add work as expected:
remove(oldEntry);
add(newEntry);
// And you'll want to repeat this for as many duplicates as there are of oldEntry.
至於doubleBag
方法,您需要一些方法來遍歷條目,然后復制它們:
Node currentNode = head;
Node newHead = null;
Node newTail = null;
while (currentNode != null) {
Node first = new Node(currentNode.data);
Node second = new Node(currentNode.data);
first.next = second;
if (newHead != null) {
newTail.next = first;
newTail = second;
} else {
newHead = first;
newTail = second;
}
currentNode = currentNode.next;
}
return newHead;
此代碼從head
開始遍歷輸入列表,創建節點的兩個副本(名為first
和second
),將它們鏈接在一起並將它們附加到一個新列表中,並在最后返回該列表。
那應該讓你開始。 另外,請注意遍歷是如何工作的,看看它與您的isDuplicated
實現(目前有一個無限循環)有何不同。 我會把它留給你來修復你的實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.