我无法在java中找到通用单链表的大小。这是我的代码(下面我将解释我是如何找到它并遇到的困难):
class List<T> {
/**
* An immutable singly-linked list.
* @param <T> the type of the list elements
*/
T head;
List<T> tail;
List(T head, List<T> tail) {
this.head = head;
this.tail = tail;
}
/** Generic helper function for list creation. You DO NOT NEED to call this function. */
static <U> List<U> node(U head, List<U> tail) {
return new List<U>(head, tail);
}
/* Getters and Setters for the head and the tail; */
public List<T> getTail() {
return tail;
}
public void setTail(List<T> tail) {
this.tail = tail;
}
public T getHead() {
return head;
}
public void setHead(T head) {
this.head = head;
}
我试图找出这样的大小:
循环遍历链表的元素,使用第一个元素进行处理,直到“下一个”指针显示null
。增加辅助变量size
。
代码:
public int size(){
int size = 0;
T temp = head;
while (temp.getTail() != null) {
temp = temp.getTail();
size++;
}
return size;
}
问题是temp.getTail()
。 Eclipse在这个特定情况下要求将变量temp
强制转换为List<T>
。但这对我来说没有任何意义,因此List<T>
应该就像是指向列表下一个元素的“下一个”指针。
有人可以如此善良,并告诉我我做错了什么以及如何解决这个问题。我真的想了解泛型(我也读了很多关于泛型的东西,但似乎还无法弄清楚如何处理这种情况)。
我将在我的测试类中使用此列表:
List<Integer> coins = List.node(1, List.node(2, List.node(5, List.node(10,
List.node(20, List.node(50, List.node(100, List.node(200, null))))))));
我会以给定的欧元金额递归计算可能的硬币组合数(值1,2,5,10,20,50,100和200)。
答案 0 :(得分:2)
应该是:
int size = 1;
List<T> temp = this;
while (temp.getTail() != null) {
temp = temp.getTail();
size++;
}
T
没有尾巴,但List<T>
确实存在,这就是你应该的温度。
即假设它是List<Integer>
,那么您的代码将如下所示:
Integer temp = head;
while (temp.getTail() != null) {
temp = temp.getTail();
size++;
}
temp
为Integer
,尾部为List<Integer>
,因此您无法为Integer
分配整数。
答案 1 :(得分:1)
当您在getTail()
中定义T
时,您试图从List<T>
调用public int size(){
int size = 1;
List<T> temp = this;
while (temp.getTail() != null) {
temp = temp.getTail();
size++;
}
return size;
}
。
可行的迭代解决方案是:
public int size() {
if (getTail() == null)
return 1;
else
return 1 + getTail().size();
}
虽然在Java中可能不太合适,但递归解决方案可能更符合您的递归数据结构:
{{1}}