Easy to understand java solution with comments


  • 0
    T
    public ListNode reverseList(ListNode head) {
        if( head == null || head.next == null ) return head;
        // Three pointers, end pointer is used to get the position of next node
        // after reversing a node.
        ListNode start = head;
        ListNode mid = head.next;
        ListNode end = head.next.next;
        // First reverse the head
        head.next = null;
        while( mid != null ){
            // reverse start and mid
            mid.next = start;
            // move forward
            start = mid;
            mid = end;
            // sanity check to avoid null exception
            if( end != null ){
                end = end.next;
            }
            
        }
        return start;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.