【发布时间】:2014-03-21 20:50:50
【问题描述】:
代码背后的概念是删除列表中大于之前元素的元素。在这种情况下,我的节点有一个 int 数据,并且可以通过它进行比较。 (这些类在扩展 Comparable
问题是当这段代码与链表一起运行时,我得到一个空点异常:
[2,5,4,3,7,6,4,2,3,4,5]
应该得到的预期列表是
[2,2]
因为 (5 > 2) 删除 5 然后 (4 > 2) 删除 4 然后 (3 > 2) 删除 3 ... 以此类推,直到它以空指针异常结束。
另一个例子是列表
[3,1,-2,3,6,-1,3,2,1]
列表最终应该是
[3,1,-2]
其中的调试代码用于显示哪些元素已被删除。
getter 方法是基本的并且工作正常。
public void deleteIncrementing() {
T largest = null;
while(head.getNext() != null || head != null) {
Node<T> temp = head.getNext();
while(temp.getValue().compareTo(head.getValue()) > 0){
largest = temp.getValue();
remove(largest);
System.out.println(largest); // debug
if(temp.getNext() == null){
break;
}
temp = head.getNext();
}
head = temp;
}
}
源自建议的伪代码:
Node<T> current = head;
Node<T> previous = null;
while(current != null) {
if (previous != null){
if (current.getValue().compareTo(previous.getValue()) > 0){
//System.out.println(current.getValue().toString());
remove(current.getValue());
}
if (current.getValue().compareTo(previous.getValue()) < 0){
//System.out.println(previous.getPrevious().getValue().toString());
//System.out.println(current.getValue().toString());
remove(previous.getValue());
}
}
previous = current;
current = current.getNext();
}
哪个仍然不正确,因为它没有考虑到第一个到最后一个元素并保留最后一个元素...有什么原因吗?
【问题讨论】:
-
我猜你应该删除
||并在以下行中添加&&while(head.getNext() != null || head != null)
标签: java nullpointerexception linked-list