Algorithm 反向链接列表-链接列表实现
这是LeetCode中的一个简单问题:反向链接列表 我有两个相似的代码,我不知道这两个代码之间有什么区别,但它输出的结果不同 第一个while循环的结果是正确的答案,但第二个有错误的答案。 而不是温度=电流。接下来,我将电流存储到temp 在while循环的最后一行,我正确地将电流切换到temp.next。 我认为他们的答案应该是一样的 但当输入{1,2,3,4,5}时,第二个解得到了错误的答案{1} 这是第二个while循环Algorithm 反向链接列表-链接列表实现,algorithm,linked-list,reverse,Algorithm,Linked List,Reverse,这是LeetCode中的一个简单问题:反向链接列表 我有两个相似的代码,我不知道这两个代码之间有什么区别,但它输出的结果不同 第一个while循环的结果是正确的答案,但第二个有错误的答案。 而不是温度=电流。接下来,我将电流存储到temp 在while循环的最后一行,我正确地将电流切换到temp.next。 我认为他们的答案应该是一样的 但当输入{1,2,3,4,5}时,第二个解得到了错误的答案{1} 这是第二个while循环 while(current != null){ ListNode
while(current != null){
ListNode temp = current;
current.next = reverse;
reverse = current;
current = temp.next;
}
在第二个代码段中,current=temp.next似乎将current从循环的顶部/开始或当前迭代设置为其nextvalue-毕竟,没有人给temp.next分配了什么。 但是在temp=current之后,两者都是同一事物的名称,current.next=reverse将覆盖需要但尚未保存的事物
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;
}
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;
}