反转链表

##题目描述 输入一个链表,反转链表后,输出新链表的表头。

思路

原地反转链表指针。
时间复杂度O(n),空间复杂度O(1)。

代码

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null)    return null;
        ListNode pre = null;
        ListNode curr = head;
        ListNode next = head.next;
        while(next != null) {
            curr.next = pre;
            pre = curr;
            curr = next;
            next = next.next;
        }
        curr.next = pre;
        return curr;
    }
}
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null)    return null;
        ListNode pre = null;
        ListNode p = null;
        while(head != null) {
            p = head;
            head = head.next;
            p.next = pre;
            pre = p;
        }
        return p;
    }
}

笔记

当while循环开始时的初设如编码所示时,根据while循环中使用了next.next,循环条件必须判断next的存在,不然会指针出错。

原文地址:https://www.cnblogs.com/ustca/p/12327030.html