-4

This only prints out "0" and I want it to print out "01"

    ListNode fakehead = new ListNode(0);
    ListNode node = null;
    fakehead.next = node;
    node = new ListNode(1);

However this prints out "012"

    ListNode fakehead = new ListNode(0);
    ListNode node = new ListNode(1);
    fakehead.next = node;
    node.next = new ListNode(2);

Why can't I set node = null and then initialize it to print out "01"?

What is the correct convention/code to do this? I would like to create new nodes on fakehead.next?

caker
  • 178
  • 2
  • 14
  • 3
    When you set `node` equal to `null` it's like throwing away the reference of what `node` points to, when you set `node` equal to a new `node` then you throw away the reference to what the `node` was previously pointing to. You should read a book that covers `LinkedLists` and other data structures or take a course. – Jonny Henly Jun 29 '16 at 02:41
  • 1
    Before asking the question you should put effort to find answer yourself. It is quite clear that effort is missing. – Gaurava Agarwal Jun 29 '16 at 02:42
  • Possible duplicate of [What is a class,reference, and an Object?](http://stackoverflow.com/questions/9224517/what-is-a-class-reference-and-an-object) – Erwin Bolwidt Jun 29 '16 at 02:47
  • 1
    Read up on the difference between an object and a reference to an object. Your variable `node` is not the object itself, but rather a reference to an object. If you change the reference `node`, this has no effect on anything that you used `node` for earlier. – Erwin Bolwidt Jun 29 '16 at 02:49

1 Answers1

2

When u first set node to null and make fakehead.next = node then fakehead.next points to null.since no space has been allocated to node,when the compiler executes this statement "node = new ListNode(1);"it allocates a new memory to node.but since you have made fakehead point to it before its initialization fakehead.next will still point to null only.thats why u get only 0 as out put.

whereas in the second case fakehead.next = node is executed after the initialization and alocation of node, so it works properly in that case.