我正在處理一個混合數據結構,它是一個有序雙鏈表,其中每個節點都包含一個SIZE數組[]。我的困難是添加方法。爲什麼這個while循環卡在無限循環中?
使用教授提供的單元測試,測試字符串被分解爲單個字符並使用提供的比較器添加到列表中。默認的測試是abcdefghijklmnopqrstuvwxyzaeiou
我寫的添加方法增加了第一個項目的罰款,但它不會超過該字符。由於該測試適用於班級中的其他學生,因此它必須是我的代碼搞砸了。
我想出了該代碼是
boolean add(E item){
Chunk<E> currentNode= head; //set lookup node to the head
if (size==0) {
//new chunk, connect it with head
Chunk<E> newNode= new Chunk<E>();
newNode.next= head;
newNode.prev=head;
head.next= newNode;
head.prev= newNode;
//add item and update counters
ll.insertItem(newNode, item);
size++;
//System.out.println(currentNode.items[0]);
}
else {
if (currentNode.next== head) {
ll.insertItem(currentNode, item);
}
while (currentNode.next != head) {
currentNode= currentNode.next;
System.out.println(currentNode.items[0]);
//if the add item is less than first item, move to previous node
if (comp.compare(item, currentNode.items[0])<0)
currentNode= currentNode.prev;
//if item fits within a chunk
if (comp.compare(item, currentNode.items[0])> 0 &&
comp.compare(item, currentNode.items[currentNode.numUsed-1])<0) {
ll.insertItem(currentNode, item);
//otherwise, move search onto next node
} else {
currentNode= currentNode.next;
}
}
}
return true;
}
ll.insertItem在陣列中確定哪個位置插入的項目的嵌套類的輔助方法,並且如果該陣列是滿的,拆分節點爲兩個節點,複製舊的節點到新的後半段,然後添加到相應的node.I該項目實現了它作爲
public void insertItem(Chunk<E> node, E item) {
if(node.numUsed==0) {
node.items[0]=item;
node.numUsed++;
}else if (node.numUsed<chunkSize) {
for (int i=0; i<=node.numUsed; i++) {
if (comp.compare(item, node.items[i])>0) {
for (int j= node.numUsed; j>i; j--) {
node.items[j+1]= node.items[j];
}
node.items[i]= item;
node.numUsed++;
}
}
} else {
//make new chunk, determine which chunk item should be added
Chunk<E> newChunk= newChunk(node);
size++;
//if item fits in new node
if (comp.compare(item, newChunk.items[0])>0) {
insertItem(newChunk, item);
} else {
insertItem(node, item); //item fits in old node
}
}
}
什麼我沒有變就是該卡在無限循環,特別是在測試字符串的第一個字符上。由於if (size==0)
條件執行,爲什麼代碼重複添加一個字符?
Addenum-添加的第一個項目
後RD
System.out.println("insertion order: "+order);
Comparator<String> comp = new StringCmp();
((CmpCnt)comp).resetCmpCnt(); // reset the counter inside the comparator
ChunkList<String> clist = new ChunkList<String>(comp);
for (int i = 0; i < order.length(); i++){
String s = order.substring(i, i+1);
clist.add(s);
}
我們也想看看'insertItem'方法。 – codaddict 2010-10-15 20:45:53
你在編輯帖子時正在編寫它 – Jason 2010-10-15 20:47:45
我們可以看到調用add方法的代碼嗎? – 2010-10-15 21:04:16