题目
输入一个链表,反转链表后,输出新链表的表头。
题解
遍历一遍链表,在遍历的过程中不断将指向关系反转,可以想到需要两个指针fast
和slow
,fast
在前,slow
在后,两个指针一同前进,每一次fast
将其next指向slow
,即反转指向关系,为了保证fast
后面的所有节点不失效,还需要第3个指针tmp
保存fast
的下一个节点。
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode fast = head.next, slow = head;
slow.next = null;
while (fast != null) {
ListNode tmp = fast.next; // 保存下一个节点
fast.next = slow; // 反转指向关系
// 两个指针同时前进
slow = fast;
fast = tmp;
}
return slow;
}
}