Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linear linked list, prepend node

Tags:

java

list

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!

like image 646
UpCat Avatar asked Sep 02 '26 11:09

UpCat


2 Answers

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.

like image 130
Mark Byers Avatar answered Sep 04 '26 00:09

Mark Byers


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.

like image 23
Amir Raminfar Avatar answered Sep 04 '26 01:09

Amir Raminfar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!