1、针对力扣的上面的单链表反转,对应的地址(力扣)
2、解法:
2.1 建立反转之后的链表头节点。ListNode pre = null;
2.2 建立当前要反转处理的节点。ListNode cur = head;
2.3 记录cur当前节点断开之后,后面链接的头节点的地址:ListNode next = cur.next;
2.4 将当前节点cur的下一个节点指向反转之后的pre。 cur.next = pre;
2.5 移动反转之后头节点pre到当前节点cur。 pre =cur;
2.6 当前节点cur只想下一个要处理的节点。 cur = next;
2.7 返回新链表的头节点:return pre;
3. 图解:其中红线为真正的步骤
4 代码
class Solution {
public ListNode reverseList(ListNode head) {
//2.1
ListNode pre = null;
//2.2
ListNode cur = head;
while(cur!=null){
//2.3
ListNode next = cur.next;
//2.4
cur.next = pre;
//2.5
pre = cur;
//2.6
cur = next;
}
//2.7
return pre;
}
}