反向LinkedList-链表实现

时间:2019-06-04 23:45:00

标签: algorithm linked-list reverse

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

第一个while循环产生正确答案,但是第二个有错误答案。 代替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;
}

2 个答案:

答案 0 :(得分:2)

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;
}

答案 1 :(得分:1)

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

相关问题