题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
三指针法:
通过三个指针 ref1、ref2、ref3,分别指向 head、head.next及待赋值节点,
- 先给 ref3 = ref2.next;赋值把 ref2.next 保存起来,以保证节点的连续查询;
- 然后反转:ref2.next = ref1; 让 ref2的 next指向其前一个节点 ref1; 同时解决了节点的 next 需要制空的问题
- 移动指针:先把指针 2 赋值给指针 1,ref1 = ref2;然后将指针 3 赋值给指针 2,ref2 = ref3;
- 遍历完成后,head.next 还指向第 2 个节点呢,需要把它制空 head.next = null;
- 循环结束条件是 ref2 为空,其实是最后一个节点为空,因为移动指针后,ref1 被 ref2赋值,ref2被ref3 赋值。最后一轮赋值后,只有 ref1 不为空,将它赋值给 head = ref1;
- 返回 head , 完成反转
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode ReverseList (ListNode head) { // write code here if (head == null || head.next == null) { return head; } // 3 pointers ListNode ref1 = head; ListNode ref2 = head.next; ListNode ref3; while (ref2 != null) { // 保存ref2.next至ref3 ref3 = ref2.next; // 反转,ref2指向前一个节点 ref2.next = ref1; // 向前移动指针 ref1 = ref2; ref2 = ref3; } // 结束后将头节点的引用置空,并将ref1给头节点 head.next = null; head = ref1; return head; } }