Charli Xbox
Charli Xbox

Reputation: 11

Javascript passing by reference issue in recursive calls

const reverseLinkedList = (ll) => {
  const head = new Node();
  const reversedLL = head;
  
  reverse(ll, reversedLL);
  return head.next;
}

const reverse = (ll, reversedLL) => {
  if (ll) {
    reverse(ll.next, reversedLL);
    reversedLL.next = new Node(ll.data);
    reversedLL = reversedLL.next;
  } 
}

I'm doing the reverse a linked list problem, but it's not running properly because I believe it's because of how javascript changes my head object at the same time as reversedLL.next = new Node(ll.data); so the linked list chaining is not persisting at the head. Is there anything I can do so that head doesn't change when I modify the reversedLL?

Upvotes: 1

Views: 291

Answers (1)

Mulan
Mulan

Reputation: 135327

I assume you need to reverse the list in place -

function reverse(ll)
{ if (ll == null) return
  let p = null
  let q = ll
  while (q)
  { p = {data: q.data, next: p}
    q = q.next
  }
  ll.data = p.data
  ll.next = p.next
}

const mylist = {data: 1, next: {data: 2, next: {data: 3, next: null}}}

reverse(mylist)

console.log(JSON.stringify(mylist))

{data: 3, next: {data: 2, next: {data: 1, next: null}}}

But you tagged this question with recursion so maybe you want to create a reversed copy instead?

function reverse(ll, p = null)
{ if (ll == null)
    return p
  else
    return reverse(ll.next, {data: ll.data, next: p})
}

const mylist = {data: 1, next: {data: 2, next: {data: 3, next: null}}}

const revList = reverse(mylist)

console.log(JSON.stringify(revList))
console.log(JSON.stringify(mylist))

{data: 3, next: {data: 2, next: {data: 1, next: null}}}
{data: 1, next: {data: 2, next: {data: 3, next: null}}}

Upvotes: 1

Related Questions