gpt4 book ai didi

algorithm - Reverse LinkedList - 链表工具

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:40:46 24 4
gpt4 key购买 nike

这是 LeetCode 中的一个简单问题:反向链表我有两个相似的代码,我无法弄清楚两者之间的区别,但它输出不同的结果。

第一个 while 循环的结果是正确的答案,但第二个 while 循环的答案是错误的。而不是 temp = current。接下来,我只是将电流存储到温度在 while 循环的最后一行,我正确地将 current 切换为 temp.next。我认为他们应该得到相同的答案但是当输入 {1,2,3,4,5} 时,第二个解决方案得到了错误的答案 {1}

ListNode reverse = null;
ListNode current = head;

while(current != null){
ListNode temp = current.next;
current.next = reverse;
reverse = current;
current = temp;
}

这是第二个 while 循环。

while(current != null){
ListNode temp = current;
current.next = reverse;
reverse = current;
current = temp.next;
}

最佳答案

while(current != null){
// This line temp is keeping the reference of current variable
ListNode temp = current;
// now temp and current both pointing to same value

// This line will make the next of current variable pointing to reverse reference
// as current and temp were same so next of temp is also pointing to the reverse
current.next = reverse;

// now the reverse will be changed and point to the current reference
reverse = current;
// so up to here reverse, temp, current all pointing to the same location
// as all are pointing same so temp.next,curr.next and reverse.next
// will store the previous reference

// current will point back to the reverse value
// no increment is done in the whole loop
current = temp.next;
}

关于algorithm - Reverse LinkedList - 链表工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56452625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com