# Java O(n) time, O(1) space solution. Temporarily modify the list. With detailed explanation

• ``````public class Solution {
if (head == null) return null;

// Calculate total length of the linked list
if (r.last != head) return null;
int totalLength = r.count;
if(totalLength == 1) return null;

// Enter half of the linked list
int half = (totalLength) / 2;
for (int i = 0; i < half; i++) {
halfNode = halfNode.next;
}

// Calculate loop length
ListNode node = halfNode.next;
int loopLength = 1;
while (node != halfNode) {
loopLength++;
node = node.next;
}

// Calculate distance from head to loop
int toLoop = (totalLength - loopLength - 1) / 2;

// Find the node where starting loop
for (int i = 0; i < toLoop; i++) {
node = node.next;
}
return node;
}

ListNode lastNode = null;
int count = 0;
while (node != null) {
ListNode next = node.next;
node.next = lastNode;
lastNode = node;
node = next;
count++;
}
Return result = new Return();
result.last = lastNode;
result.count = count;
return result;
}

private static class Return {
public ListNode last;
public int count;
}
}``````

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