如何遍历双链表并在下面创建一个新的双链表或等于或大于或等于特定值?
例如:
["A", "B", "C"].below("B") = ["A", "B"]
我得到了一个ClassCastException,所以我不知道如何实现创建一个新列表并将这些节点添加到特定值。我已经实现了自己的compareto方法,该方法正常。我的添加方法也正常。
main class:
.
.//some code
LinkedList<Item> itemList = new LinkedList<>();
itemList.add(....(..)));
.//some code
print(itemList.below(new Drink("Cola", 1.0, 1.0)));
.
.//some code
public class LinkedList <T extends Comparable<? super T>> implements List<T>
{
..
private Node <T> head;
private Node <T> last;
..//some code
public void add(T value)
{ ..}
public LinkedList <T> below (T value)
{
LinkedList <T> b = new LinkedList<>();
Node <T> curr = new Node<>(value);
Node <T> start = this.head;
while(start.next != null && curr.data.compareTo(start.next.data) <= 0 )
{
b.add((T) start); //ClassCastException
start = start.next;
}
return b;
}
private static class Node <T>
{
private T data;
private Node <T> next;
private Node <T> prev;
private static int counter = 0;
private final int ID;
private Node(T data)
{
this.data = data;
this.ID = counter;
counter++;
}
}
}
ClassCastException
是因为start
被定义为Node<T>
并且以下代码将Node<T>
对象强制转换为T
对象,这是一个运行时错误。
b.add((T) start); //ClassCastException
你可能打电话给:
b.add(start.data)
然而,data
标记为private
。所以要么标记它public
,要么更好,在getData()
中添加一个访问者Node
方法。