linked-list - 反转链表时遇到问题
问题描述
我正在尝试使用 java 反转链表并写在下面的代码中。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur=head,prev=null,newHead=null;
while(cur!=null)
{
newHead=cur;
newHead.next=prev;
prev=newHead;
System.out.println(1);
cur=cur.next;
}
return newHead;
}
}
我不明白为什么循环在这里只执行一次。难道我做错了什么?
解决方案
发生这种情况是因为你已经改变cur.next
了分配newHead.next=prev;
,使之null
。意识到它newHead
引用了与当时相同的对象cur
。
cur.next
您应该在此更改发生之前保存 的原始值:
ListNode cur = head, prev = null, newHead = null, next;
while (cur != null)
{
newHead = cur;
next = cur.next; // <--- save original value of `cur.next`
newHead.next = prev;
prev = newHead;
cur = next; // <--- use that original value here
}
推荐阅读
- qt - 在 WebEngineView 中禁用 qml 的上下文菜单
- python - Python:使用 Numpy 删除“for”循环
- sorting - 按字符串的最后一个字符对压缩列表(字符串,'Line2D' 的实例)进行排序
- typescript - 为什么需要虚拟属性才能使类型保护起作用?
- python - 基于不同值掩码的数组求和
- r - 将国家分为热带与非热带 R
- swift - 循环一系列 withAnimation 函数
- c++ - 在延迟加载的共享库中使用单例
- python - IndexError:列表索引超出范围,即使打印单个列表和索引似乎没有错误
- docker - docker容器中的rsyslog服务无法执行logrotation