gpt4 book ai didi

java - 单向链表 - get 和 add 方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:05:13 24 4
gpt4 key购买 nike

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

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

我在我的程序中苦苦挣扎的是添加和获取方法。我不断收到错误 incompatible types: SLList<T>.Node cannot be converted to int还有incompatible 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

最佳答案

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

i = u.next;

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

关于java - 单向链表 - get 和 add 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com