剑指 Offer 24. 反转链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        //判空
        if(head == null || head.next == null){
            return head;
        }
        //定义三个节点,他们的关系是  pre <--  now <-- next
        ListNode pre = null;
        ListNode now =head;
        ListNode next = null;

        while(now !=null){
            //保存当前节点的下一个节点信息
            next = now.next;
            //翻转链表的指向
            now.next = pre;
            //整体前移,进行下一次翻转
            pre = now;
            now = next;
        }
        return pre;
    }
}
原文地址:https://www.cnblogs.com/peanut-zh/p/14133988.html