Singly Linked List - get and add methods

Dobrikella :

So I'm trying to implement an SLList class by completing the implementations:

get(i), set(i, x), add(i, x), and remove(i) operations, each running in O(1 + i) time.

What I'm struggling with my program is the add and get methods. I keep getting the errors incompatible types: SLList<T>.Node cannot be converted to int and also incompatible types: SLList<T>.Node cannot be converted to int.

I'm very confused as to how to fix them. I just learned about linked lists today and I'm struggling to grasp the concept of them. Any help or hints would be really 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 the type of each function T and void must stay as they are. Also I believe I should include the IndexOutOfBoundsException part in my code.

If you guys want to see my full code its here: https://pastebin.com/nJ9iMjxj

Mohsen_Fatemi :

In your node class, the type of next is node, while in your get method, you are assigning a node to an integer variable :

i = u.next;

i don't see the whole implementation of yours, but i think it should be u = u.next;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306231&siteId=1