我正在尝试实现在Java中以相反顺序排序的链接列表,但add方法给了我奇怪的结果。
我必须实现这个列表(不能只使用LinkedList
,这是我在实践中会做的)我必须使用递归。
我正在插入的数组来测试代码:
[-20, 0, -10, 5, 12, 1, -100, -50, -101, 200]
Heres是SortedLinkedSet中的相关位:
public boolean add(T el) {
if (firstNode == null || el.compareTo(firstNode.getValue()) > 0 ) {
//the new element will become the new first node
firstNode = new SortedLinkedSetNode<T>(el, firstNode);
return true;
} else {
return firstNode.add(el);
}
}
这是SortedLinkedSetNode:
public boolean add(T el) {
//reduction steps
if(el == null)
return false;
else if(contains(el))
return false;
else if(el.compareTo(this.getValue()) <= 0)
{
if(next == null)
{
next = new SortedLinkedSetNode<T>(el);
return true;
}
return next.add(el);
}
else
{
//base case
SortedLinkedSetNode<T> newNode = new SortedLinkedSetNode<T>(el);
newNode.next = this.next;
this.next = newNode;
return true;
}
}
输出:
[200, 12, 5, 0, 1, -20, -10, -100, -50, -101]
在if(next == null)
之前将else if
支票移至else if(el.compareTo(this.getValue()) <= 0)
区块会产生相同的结果。
我几个小时都无法对这些结果做出正面或反面:\
为了测试,我一直在检查内存中的列表。 在有人问之前,这确实是功课。我不是在寻找帮助,只是帮助。
答案 0 :(得分:0)
您的基本情况不对。如果el
&gt; this.getValue()
您仍在当前节点之后插入它,这会破坏您的订单不变。
您可以做的一件事是在当前后插入一个新节点,然后将新节点的值更改为当前节点的值,将当前节点的值更改为el
。