crazymind
crazymind

Reputation: 169

Why does my add() method in LinkedList not working?

I just implement add() method in my Linkedlist but it does not really work. I think "current = new Node(node.data);" makes the object point to a new object instead of update the original one but I don't know how to solve it. Is there any way that I can update this node properly? Please help, thanks.

class Node{
    int data;
    Node next; 
    Node(int data){
        this.data = data;
        this.next = null;
    }
    Node(int data, Node next){
        this.data = data;
        this.next = next;
    }
}
class LinkedList{
    protected Node head;
    protected int size;
    LinkedList(){};

    void add(int data)
    {
        Node node = new Node(data);
        if (head == null) {
            head = node;
        }else {
            Node current = head;
            while(current != null) {
                current = current.next;
            }
            current = new Node(node.data);
        }
        size++;
    }
    public int getSize() {
        return size;
    }
    public String toString()
    {
        Node current = head;
        String result = "";
        while(current != null) {    
            result += current.data +"->";
            current = current.next;
        }
        return result;
    }
}

Upvotes: 2

Views: 1995

Answers (2)

GhostCat
GhostCat

Reputation: 140457

You are almost there. Your problem lies here

while(current != null) {
... }

current = new Node(node.data);

That creates a new node, which should sit on the very end of your list. But you only assign the new instance to a local variable ... which then gets lost, because the method ends.

Instead, you have to change your loop until you find the last entry that isn't null, so that current.next == null. To then simply go:

current.next = new Node(node.data);

Upvotes: 1

SynchroDynamic
SynchroDynamic

Reputation: 386

In a LinkedList, the values are added to the top per say. It is not like adding to an array. So when you add a new Node, instead of trying to add it to the end, you would just add it as the new head element.

It is as easy as:

public void add(T item) {

    Node<T> next = new Node<>(item, head);
    this.head = next;
    size++;

}

If you want to restrict your LinkedList to only int, then you can replace T with int.

I hope this helps

Upvotes: 0

Related Questions