题目描述
输入一个链表,反转链表后,输出新链表的表头。
1、思路分析
为保证思路的完整性,一开始需考虑特殊情况,即链表结点为空或者只有头结点的时候,直接返回链表本身。初始思路我想用三个指针分别前一个、当前和下一个结点,其实通过移动head可以充当当前指针,因此我们再另外新建pre、next两个指针即可。再在while循环中交换三个指针指向的下一个指针位置,这与交换两个数字的思路比较像,需要预先存储即将被改变的,以免被覆盖。最后返回pre指针即可。
2、代码

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode pre = null;
        ListNode next = null;
        while(head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}