需要用一个虚节点来保存
class Solution {
public ListNode reverseList(ListNode head) {
//头插法
ListNode dumpyHead = new ListNode();
//dumpyHead.next = head;
ListNode cur = head;
while(cur != null) {
//保存下一个节点
ListNode next = cur.next;
//断开链表
cur.next = null;
//上一个头节点
ListNode prev = dumpyHead.next;
// 新节点挂在虚拟头结点
dumpyHead.next = cur;
//当前头节点接上上一个头结点
cur.next = prev;
//指针移动
cur = next;
}
return dumpyHead.next;
}
}