3

I have a problem understanding an exercise. I have to develope a linear linked list. But I do not have to to distinguish between list and node.

The constructor Node should create a node and prepend it to the list that is passed as a parameter.

Normally I would go through the list and append a node at the end of it. Here is my code.

class Node{ Object data; Node link; public Node(Object pData, Node pLink){ this.data = pData; this.link = pLink; } public String toString(){ if(this.link != null){ return this.data.toString() + this.link.toString(); }else{ return this.data.toString() ; } } public void inc(){ this.data = new Integer((Integer)this.data + 1); } } 

Maybe I have just learned to much today and my brain can't take more inforamtion:D please help!

1
  • 1
    Looks like you are doing it right! Commented Jan 13, 2011 at 21:03

2 Answers 2

1

You need modify the next pointer of the node to point to the list that is passed in as a parameter.

This is in fact what your code is already doing. I have tried running it and it gives the correct result. :)

You might want to consider including a separator in your implementation of toString so that the output is still clear when the numbers in the data get larger than 9.

Sign up to request clarification or add additional context in comments.

Comments

1

I am not sure what you are asking but i think this is what you want so here it goes.

Lets say you already have the head

Node head = ... 

you can append to this by doing

head = new Node(..., head) 

Notice I am assigning head again so now the head points to the newly created node.

1 Comment

As Mark says, you area already doing this. But hopefully my answer helps to show how to use it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.