Easy Java Iterative solution with comments

  • 0
    public ListNode reverseList(ListNode head) {
            // Check if the list is empty and return null if so.
            if(head==null) return head;
            ListNode toMove;
            ListNode newHead=head;
            // The idea is to move the head along the length of the 
            // linked list while moving the node that is next to head
            // to the first position.
            // We iterate until there is no next node for the head.
            while(head.next!=null) {
                // This is the node that will be moved.
                // The below line moves the head to a new position by pointing the
                // to the node that is next to the next node of head.
                // This line moves the toMove node to the beginning position.
                // toMove is the now the head node.
            return newHead;

Log in to reply

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