-1

我的数据结构如下:

[对象] -> [对象] -> [对象]

每个对象都有一个指向另一个对象的右指针。

while (currentParcel.getRight() != null) {
    currentParcel = currentParcel.getRight();
}

此代码进入无限循环。

按照我的逻辑,它应该尽可能地向右移动,并且只有当它达到 null 时,currentParcel 对象才应该是最后一个带有指向 null 的指针的对象(右侧没有对象)。

如何解决无限循环?

我试过用以下方式写它:

boolean found = false;
try {
   while (found == false) {
       currentParcel = currentParcel.getRight();

       if (currentParcel.getRight() == null)
       {
           currentParcel.addRight(p);
           System.out.println(currentParcel);
           found = true;
       } 

   }
} 
catch (NullPointerException e) {}

但这对我不起作用。它只是没有尽可能地向右移动。

4

2 回答 2

1

You've got a circular link in your linked list structure. To debug this, either use a debugger or println the objects in your while loop to see what they are. This way you will find the problem. Make sure your objects have a decent toString() method and print them out inside of the loop for one way to identify your circular connection. Also, you don't have to have "the last points to the first" for this to occur, but rather all you need is just for a circular connection to exist somewhere. You'd best find it.

于 2013-05-02T23:00:43.853 回答
0

你的循环没问题,问题出在其他地方,这工作正常

    Parcel p1 = new Parcel();
    Parcel p2 = new Parcel();
    Parcel p3 = new Parcel();
    p1.setRight(p2);
    p2.setRight(p3);
    Parcel currentParcel = p1;
    while (currentParcel.getRight() != null) {
        currentParcel = currentParcel.getRight();
    }
于 2013-05-02T22:58:00.457 回答