剑指Offer(书):反转链表

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

分析:要分清他的前一个节点和后一个节点,开始的时候前节点为null,后节点为head.next,之后,反转。

    public ListNode ReverseList(ListNode head) {
               if (head == null) {
            return null;
        }
        if(head.next==null){
            return head;
        }

        ListNode preNode = null;
        ListNode currentNode = head;
        ListNode afterNode = head.next;
        while (currentNode!=null){
            currentNode.next=preNode;
            preNode = currentNode;
            if (afterNode.next == null) {
                afterNode.next=currentNode;
                break;
            }
            currentNode=afterNode;
            afterNode = afterNode.next;
        }
        return afterNode;
    }
原文地址:https://www.cnblogs.com/liter7/p/9445089.html