开发者

Linear linked list, prepend node

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() ;
        }
    }开发者_如何学Go

    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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜