- 前言
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
- 存在一个新的链表的头结点
- 所有节点必须遍历一遍,但是每次遍历跟操作指针要分开,不然链表断裂后无法继续遍历,则存在游标cur
- 整体实现
根据1和2可以写出以下代码,分析后错误明显 : 转链表后,current无法继续遍历
class Solution {
/**
* 将NULL也视作一个节点
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
// 新链表的头节点
ListNode newPrev;
// 创建游标遍历整个链表
ListNode cur = head;
while (cur.next != null) {
// 移动游标
cur = cur.next
// ......更多有关newPrev的逻辑
}
// cur遍历至旧的链表尾,即是新的链表头
return cur;
}
}
- 细节分析
以上是第一个想到的办法,很显然,不可能实现。则有一下思考
1.按照整理实现的思路,current实现翻转,要将next指向新链表的头节点。
2.current指向上个节点后,新增的节点就为新链表的头节点。
3.新链表的第一个节点为null;
根据1、2、3有以下思路
显然在操作current指针时,需要新建个指针保留断开连接后的子链表
完成以上步骤后
1.不论current还是childList都是为了遍历子链表,而之前的节点已断开,函数返回newPre才是翻转后的链表头节点
2.当current == null 的时候,newPre刚好指向完整的新链表,所以修改迭代条件为while(cur != null)
- 最终代码
class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
/**
* 将NULL也视作一个节点
* @param head
* @return
*/
public ListNode reverseList(ListNode head) {
// 若把NULL也作为一个节点的话,NULL是新的链表的第一个头节点
ListNode newPrev = null;
// 创建游标遍历整个链表
ListNode cur = head;
while (cur != null) {
ListNode childList = cur.next;
cur.next = newPrev;
newPrev = cur;
cur = childList;
}
return newPrev;
}
}
时间复杂度:O(n) 空间复杂度:O(1)
- 拓展
链表反转递归解法见:
https://blog.csdn.net/chenghan_yang/article/details/94908013