繁体   English   中英

如何在java中查找通用单链表的大小

[英]How to find the size of a generic singly-linked list in 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;
}

我试图找出这样的大小:循环遍历链表的元素,用第一个元素进行处理,直到“下一个”指针显示为null 增加辅助变量size 码:

    public int size(){
    int size = 0;

    T temp = head;
    while (temp.getTail() != null) {
        temp = temp.getTail();
        size++;
    }

    return size;
}

问题是temp.getTail() Eclipse在这个特定情况下要求将变量tempList<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)。

它应该是:

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

当你在List<T>定义时,你试图从T调用getTail()

一个可行的迭代解决方案是:

public int size(){
    int size = 1;

    List<T> temp = this;
    while (temp.getTail() != null) {
        temp = temp.getTail();
        size++;
    }

    return size;
}

虽然在Java中可能不太合适,但递归解决方案可能更符合您的递归数据结构:

public int size() {
    if (getTail() == null)
        return 1;
    else
        return 1 + getTail().size();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM