ratboy
ratboy

Reputation: 63

LinkedList: What to substitute for node on the last node?

This is what my constructor looks like in my LinkedNode class:

int info;
LinkedNode next;

public LinkedNode(int info, LinkedNode next) { 
    this.info = info;
    this.next = next;
}

In my Test (main) class, when I try to create the nodes as such:

LinkedNode d = new LinkedNode(40, null);
LinkedNode c = new LinkedNode(30, d);
LinkedNode b = new LinkedNode(20, c);
LinkedNode a = new LinkedNode(10, new LinkedNode(20, LinkedNode(30, LinkedNode(40, null))));

, then I get a compiler error telling me

The method LinkedNode(int, null) is undefined for the type of Test

And it's true since the 2nd parameter of my constructor is of LinkedNode type, but then how do I signify that the last node's next is empty?

Upvotes: 1

Views: 56

Answers (3)

Day-g
Day-g

Reputation: 11

I tried with your code but it works when add new keyword.

LinkedNode c = new LinkedNode(10, new LinkedNode(20, new LinkedNode(30, new LinkedNode(40, null))));

Upvotes: 1

user7491376
user7491376

Reputation:

LinkedNode d = new LinkedNode(40, null);
LinkedNode c = new LinkedNode(30, d);
LinkedNode b = new LinkedNode(20, c);
LinkedNode a = new LinkedNode(10, new LinkedNode(20, new LinkedNode(30, new LinkedNode(40, null))));

You can also use this tutorial

Upvotes: 1

Holger Jaekel
Holger Jaekel

Reputation: 106

The following code would be syntactically correct (the new keyword was missing as chatton already said)

LinkedNode a = new LinkedNode(10, 
    new LinkedNode(20, 
        new LinkedNode(30, 
            new LinkedNode(40, null))));

But maybe you mean

LinkedNode a2 = new LinkedNode(10, b);

instead?

Upvotes: 2

Related Questions