【问题标题】:Singly Linked List - get and add methods单链表 - 获取和添加方法
【发布时间】:2020-02-09 11:18:02
【问题描述】:

所以我试图通过完成实现来实现一个 SLList 类:

get(i)set(i, x)add(i, x)remove(i) 操作,每个操作都在 O(1 + i) 时间内运行。

我正在为我的程序苦苦挣扎的是 add 和 get 方法。我不断收到错误incompatible types: SLList<T>.Node cannot be converted to intincompatible types: SLList<T>.Node cannot be converted to int

我很困惑如何解决它们。我今天刚刚了解了链表,我正在努力掌握它们的概念。任何帮助或提示将不胜感激。

public T get(int i) {
    // TODO: Implement this
    Node u = head;
    for(int j = 0; j < i; j++){
        i = u.next;
    }
    return u;
    if (i < 0 || i > n - 1) throw new IndexOutOfBoundsException();
    return null;
}


public void add(int i, T x) {
        Node u = new Node();
        u.x = x;
        if (i == 0) {
            head = u;
        } else {
            tail.next = u;
        }
        tail = u;
        i++;
        return true;
        if (i < 0 || i > n) throw new IndexOutOfBoundsException();
}

我应该提到每个函数 T 的类型,并且 void 必须保持原样。另外我相信我应该在我的代码中包含 IndexOutOfBoundsException 部分。

如果你们想在这里查看我的完整代码:https://pastebin.com/nJ9iMjxj

【问题讨论】:

  • 您的 get 方法返回 Node 而不是 T。并且您的add 方法不应返回true,因为它已被声明为void
  • 我可以看看你的node 课程吗?

标签: java node.js linked-list queue singly-linked-list


【解决方案1】:

在您的node 类中,next 的类型是node,而在您的get 方法中,您将node 分配给一个整数变量:

i = u.next;

我没有看到你的整个实现,但我认为应该是u = u.next;

【讨论】:

    【解决方案2】:

    在您的get 方法中,您尝试将Node 分配给第5 行的int 变量。相反,您应该编写u=u.next;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多