提问人:Charli Xbox 提问时间:4/14/2021 更新时间:4/14/2021 访问量:223
递归调用中的 Javascript 按引用传递问题
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;
}
}
我正在反向处理链表问题,但它无法正常运行,因为我相信这是因为 javascript 如何同时更改我的对象,因此链表链接不会保留在头部。我能做些什么来使我在修改 ?head
reversedLL.next = new Node(ll.data);
head
reversedLL
答:
1赞
Mulan
4/14/2021
#1
我假设你需要把清单放在位——reverse
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}}}
但是你用递归标记了这个问题,所以也许你想创建一个反向副本?
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}}}
评论
reversedLL
是与head
reversedLL
reverse
reversedLL
head
head
reversedLL
reversedLL
if
reversedLL
reverse
reversedLL
reversedLL
reversedLL = reverse(ll.next, reversedLL);