剑指offer15_链表反转
题目描述
输入一个链表,反转链表后,输出新链表的表头。
假设有两个指针的话,分析之后发现是没法实现的,因为一旦反转之后,node.next就不再是原next了,而是前面的节点,这显然是不对的。所以指针实现的话,需要三个指针,其中第三个指针负责记录原next节点。
借用别人博客里面的思路:
当前节点为head,首先实现反转head.next=pre,然后三个节点都后移一位到next,直到结束。
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return null;
ListNode pre = null;
ListNode next = head.next;
while(head != null) {
head.next = pre;//反转
pre = head;
head = next;
if(head != null)next = head.next;//三个指针均后移一位,注意必须先head移位再next
//注意head==null就没有head.next了,所以要先有个空指针的判断
}
return pre;//pre指针会停在null的前一位
}
}