[英]Removing and adding items from a linked list (Java)
當我嘗試測試用例時,我編寫的代碼不起作用,但我不明白為什么。 我的代碼在2種方法中。 如果您需要其余的類文件,可以在https://www.cs.berkeley.edu/~jrs/61b/hw/hw3/中找到它們。 注意我編輯了節點類並創建了set和get方法。 難道是給我錯誤還是我的解決方案是錯誤的?
/**
* squish() takes this list and, wherever two or more consecutive items are
* equals(), it removes duplicate nodes so that only one consecutive copy
* remains. Hence, no two consecutive items in this list are equals() upon
* completion of the procedure.
*
* After squish() executes, the list may well be shorter than when squish()
* began. No extra items are added to make up for those removed.
*
* For example, if the input list is [ 0 0 0 0 1 1 0 0 0 3 3 3 1 1 0 ], the
* output list is [ 0 1 0 3 1 0 ].
*
* IMPORTANT: Be sure you use the equals() method, and not the "=="
* operator, to compare items.
**/
public void squish() {
// Fill in your solution here. (Ours is eleven lines long.)
SListNode previous = head;
SListNode next;
SListNode root = head;
int x = 1;
for (int counter = 0; counter < size; counter++)
{
next = previous.getNext();
if (!previous.equals(next))
{
root.setNext(next);
root = next;
x++;
}
previous = previous.getNext();
}
size = x;
}
/**
* twin() takes this list and doubles its length by replacing each node
* with two consecutive nodes referencing the same item.
*
* For example, if the input list is [ 3 7 4 2 2 ], the
* output list is [ 3 3 7 7 4 4 2 2 2 2 ].
*
* IMPORTANT: Do not try to make new copies of the items themselves.
* Make new SListNodes, but just copy the references to the items.
**/
public void twin() {
// Fill in your solution here. (Ours is seven lines long.)
SListNode previous = head;
SListNode next;
for (int counter = 0; counter < size; counter++)
{
next = previous.getNext();
previous.setNext(previous);
previous = previous.getNext();
previous.setNext(next);
}
size = 2*size;
}
我認為這可能是列表長度在完成時未更新的問題。 當您忘記這樣做時,測試用例可能會尋找並打印出錯誤消息! (沒有餅干!)
雖然我不確定,但這似乎是最合理的解釋(查看測試文件,看看他們如何明確聲明檢查所有不變量)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.