Singly Linked List – Get and add methods
So I’m trying to implement a SLList class by completing the implementation:
get(i
), set(i, x), add(i, x),
and remove(i) operations, each run in O(
1 + i)
time.
What I’m struggling with in my program is adding and getting methods. I keep getting the error incompatible types: SLList<T>. Node cannot be converted to int
and incompatible types: SLList<T>. Node cannot be converted to int
.
I’m confused about how to fix them. I just learned about linked lists today and I’m trying to grasp their concepts. Any help or tips are greatly appreciated.
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();
}
I should mention that the types of each function T and void must be left as is. Also, I think I should include the IndexOutOfBoundsException section in my code.
If you want to see my full code here: https://pastebin.com/nJ9iMjxj
Solution
In your node
class, the next
type is node, and in your get
method, you are assigning node
to an integer variable:
i = u.next;
I
don’t see your whole implementation, but I think it should be u = u.next;