【发布时间】:2014-10-07 06:08:35
【问题描述】:
以下代码确保元素以排序方式插入到链表中。
在了解了这背后的逻辑后,我决定自己测试一下。但是,当我编写我的代码版本时,如下所示。
public class SortedList {
private Node first;
public SortedList() {
first = null;
}
public boolean isEmpty() {
return first == null;
}
public void insert(int j) {
Node newNode = new Node(j);
Node previous = null;
Node current = first;
while (current != null && j > current.iData) {
previous = current;
current = current.next;
}
if (previous == null)
first = newNode;
else
newNode.next = current;
previous.next = newNode;
}
public Node remove() {
Node temp = first;
first = first.next;
return temp;
}
public void displayList() {
System.out.println("First to -----> Last");
Node current = first;
while (current != null) {
current.display();
current = current.next;
}
}
}
节点类
public class Node {
public int iData;
public Node next;
public Node(int id) {
iData = id;
}
public void display() {
System.out.println(iData + " ");
}
}
测试班
public class SortedListApp {
public static void main(String[] args) {
SortedList list = new SortedList();
list.insert(20);
list.insert(40);
list.displayList();
list.insert(10);
list.insert(30);
list.insert(50);
list.displayList();
list.remove();
list.displayList();
}
}
两者之间的唯一区别是在我的版本中,当 while 循环终止时。我首先将 newNode 的下一个值设置为当前值,然后将previous 的下一个值设置为新节点。在发布的原始代码中,他们将其反转。由于某种原因,这会引发空指针异常。我想知道为什么?
据我了解,一旦新节点找到插入位置。我们引用了前一个节点和当前节点,我们试图将新节点插入前一个节点和当前节点的中间。因此我所做的就是将新节点的下一个节点设置为当前节点,然后将前一个节点的下一个节点设置为新节点。
请告诉我哪里错了。
【问题讨论】:
标签: java data-structures linked-list