Java 为什么这个while循环卡在无限循环中?
我正在研究一种混合数据结构,它是一个有序的双链表,其中每个节点都包含一个大小为[]的数组。我的困难是加法 使用教授提供的单元测试,测试字符串被分解成单个字符,并使用提供的比较器添加到列表中。默认测试是Java 为什么这个while循环卡在无限循环中?,java,data-structures,infinite-loop,Java,Data Structures,Infinite Loop,我正在研究一种混合数据结构,它是一个有序的双链表,其中每个节点都包含一个大小为[]的数组。我的困难是加法 使用教授提供的单元测试,测试字符串被分解成单个字符,并使用提供的比较器添加到列表中。默认测试是abcdefghijklmnopqrstuvxyzaeou 我编写的add方法可以很好地添加第一项,但不会超过该字符。既然考试对班上其他学生有效,那一定是我的代码把事情搞砸了 我想出的密码是 boolean add(E item){ Chunk<E> currentNode= h
abcdefghijklmnopqrstuvxyzaeou
我编写的add方法可以很好地添加第一项,但不会超过该字符。既然考试对班上其他学生有效,那一定是我的代码把事情搞砸了
我想出的密码是
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;
}
添加第一项后,您不会增加numUsed 这: 应该是:
if(node.numUsed==0) {
node.items[0]=item;
node.numUsed++;
}
我们还希望看到
insertItem
方法。您是在我编辑postcan时编写的,我们看到了调用add方法的代码?当您使用IDE的调试器单步执行代码时会发生什么情况?不幸的是,问题仍然存在,因为我在add()中更改了node.numUsed方法对node.numUsed-1进行更正,以将项与空值进行比较。结果表明,问题完全出在其他地方。你的回答解决了眼前的问题。
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);
}
if(node.numUsed==0) {
node.items[0]=item;
}
if(node.numUsed==0) {
node.items[0]=item;
node.numUsed++;
}