algorithm - 关于反向链表的问题(leetcode 206)
问题描述
我知道我的代码完全错误,但我不知道我哪里做错了,
谁能指出并解释我做错了什么?
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode prev = null;
ListNode current = head;
ListNode nextNode = head.next;
while (nextNode != null) {
prev = current;
current = nextNode;
current.next = prev;
nextNode = nextNode.next;
System.out.println(nextNode.val);
}
return current;
}
解决方案
变化:
头。下一个=空;// 使列表的末尾为空
当前.下一个=上一个;// current 是对节点的引用,因此对它的更改将同时更改引用 nextNode 的节点
public ListNode reverseList(ListNode head) { if (head == null) { return head; } ListNode prev = null; ListNode current = head; ListNode nextNode = head.next; head.next = null; // to make the end of the list as null while (nextNode != null) { prev = current; current = nextNode; nextNode = nextNode.next; // first get next node, before ... current.next = prev; // ... overwriting it here // System.out.println(nextNode.val); } return current; }
推荐阅读
- salesforce - 如何从订单对象中获取机会拆分记录
- javascript - AngularJS ng-if 变量只工作一次
- python-3.x - 如何绘制共享相同 x 轴的 2 个子图
- python - 查找平均值并显示来自 csv 的最大数据(列表索引必须是整数或切片,而不是 str)#python
- javascript - 如何将axios返回的json保存在变量中?
- arduino - 如何在没有运动时阻止 PIR 传感器发送高输出
- python - 蜘蛛完成后返回scrapy项目
- javascript - 如何过滤深层嵌套数据?- Javascript JSON
- vue.js - 100% 动态多租户 VueJS/.NetCore 应用程序中的 SSR(内容、组件等)
- java - 将图像/文件上传到服务器时使用 MultipartBody.Builder 的问题