-1

我将数据存储在一个简单的链表结构中,这两个循环在 java 中有什么区别?我认为第一个与第二个相同,但代码更少,但它不起作用。

//1
temp = list.firstElement;
while (temp != null) {
  temp = temp.nextElement;
}
temp = *data*;

//2
if (list.firstElement == null) {
  list.firstElement = *data*;
}
else {
  temp = list.firstElement;
  while (temp.nextElement != null) {
    temp = temp.nextElement;
  }
  temp.nextElement = *data*;
}

为什么第二个在列表中添加了一些东西,但第一个没有?(第一个元素仍然为空)

4

3 回答 3

2

在第一个片段中,temp = data;所做的只是更改temp变量所指的内容 - 它不会修改列表中的任何对象。

+--+  +--+  +--+  +--+             temp->+--+         
|  |->|  |->|  |->|  |->null             |  |
+--+  +--+  +--+  +--+             data->+--+

在第二个片段中,when tempis something in your listtemp.nextElement = data;将分配data给列表中实际找到的内容,从而修改列表。

             temp---+
                    V 
+--+  +--+  +--+  +--+             
|  |->|  |->|  |->|  |-------->+--+   
+--+  +--+  +--+  +--+         |  |
                         data->+--+
于 2013-11-04T22:58:19.447 回答
1

在第一个循环中,直到当前元素为空,然后您将某些内容分配给该值,但没有人指向您的新值,因此它不可见。

使用第二个循环,直到 nextElement 为空,然后分配它,以便有人指向它。

于 2013-11-04T22:56:33.537 回答
1

您恰好在 temp==null 时退出第一个循环,即您已经完全退出列表。

当 temp.nextElement==null 时,您退出第二个循环,这尤其意味着 temp!=null。这再次意味着 temp 指向列表的最后一个元素,您可以成功设置其 nextElement 字段。

于 2013-11-04T22:55:48.653 回答