如何在java中找到通用单链表的大小
在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;
}
我试着找出这样的尺寸:
循环遍历链表的元素,与第一个元素对齐,直到“next”指针显示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)
# 1 楼答案
当
List<T>
中定义了T
时,您试图从getTail()
调用它一个可行的迭代解决方案是:
尽管在Java中可能不可取,但递归解决方案可能更符合递归数据结构:
# 2 楼答案
应该是:
T
没有尾巴,但是List<T>
有尾巴,这就是你的临时工应该有的样子ie假设它是一个
List<Integer>
,那么您的代码将如下所示:temp
是一个Integer
,尾部将是一个List<Integer>
,因此不能将一小部分整数分配给Integer