反向链接列表 - 链表实现



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

第一个循环结果正确答案,但第二个有错误的答案。 而不是temp = current.接下来,我只是将电流存储到温度 在 while 循环的最后一行,我正确地将电流切换到 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;
}

在第二个代码段中,似乎current = temp.next从循环顶部/开始或当前迭代current设置为其next值 - 毕竟,没有人为temp.next分配某些东西。
但是在temp = current之后,两者都是同一事物的名称,并且current.next = reverse覆盖需要且尚未保存的内容。

相关内容

  • 没有找到相关文章

最新更新