有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在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)


共 (2) 个答案

  1. # 1 楼答案

    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();
    }
    
  2. # 2 楼答案

    应该是:

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

    T没有尾巴,但是List<T>有尾巴,这就是你的临时工应该有的样子

    ie假设它是一个List<Integer>,那么您的代码将如下所示:

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

    temp是一个Integer,尾部将是一个List<Integer>,因此不能将一小部分整数分配给Integer