0

I'm trying to understand Javascript's pointer by implementing my own LinkedList. The ListNode class looks like this:

function ListNode(val) {
    this.val = val;
    this.next = null;
}

I then have a function to create a LinkedList with numbers from 0 to 100:

function fillList() {
    let output = new ListNode();
    let curr = output;

    for(let i = 0; i < 100; i++) {
        if(curr) {
            curr.val = i;
        } else {
            curr = new ListNode(i);
        }
        curr = curr.next;
    }

    return output;
}

The problem is after the return, output has nothing but 0 as its value. This means that the for loop doesn't work, especially when move curr to its curr.next and assign a ListNode to it.

The logic seems to be fine for me, what goes wrong?

AustinP
  • 63
  • 6
  • Javascript doesn't have [pointers](https://stackoverflow.com/questions/17382427/are-there-pointers-in-javascript) so the logic above (which works in c/c++) won't work – Sunil Chaudhary Dec 28 '19 at 11:38

1 Answers1

0

Javascript doesn't have pointers, perhaps what you are referring to is the fact that in Javascript objects are always references? So that this.next is a reference to an object. You can implement your function like so:

function fillList() {
  let output = new ListNode();
  let curr = output;

  for (let i = 0; i < 100; i++) {
    curr.val = i;
    curr.next = new ListNode();
    curr = curr.next;
  }

  return output;
}
Collierre
  • 946
  • 8
  • 16
  • I understand it now, so because `null` is a value type, not a reference type, assign `curr = curr.next` before creating the object will turn it into a value type instead. Thus it's not referenceable. Thanks. :) – AustinP Dec 28 '19 at 22:30