I'm trying to check if the last node of a linked list points to the head. This code seems to give a positive result for the problem, but also gives a false positive for a list that contains a node pointing to a non-head node.
I've been trying different things such as checking if the slow node is equal to the head at the return true point, but that doesn't seem to work.
public boolean isLinkedToStart(Node head) {
if (head == null) {
return false;
}
Node fast = head.next;
Node slow = head;
while (fast != null && fast.next != null) {
if (fast.next.next == slow) {
return true;
}
fast = fast.next.next;
slow = slow.next;
}
return false;
}
Any suggestions?
public boolean isLinkedToStart(Node head) {
if (head == null) {
return false;
}
Node fast = head.next;
Node slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if(slow.next == head)
return true;
if (fast == slow)
return false;
}
return false;
}
Okay, third time is a charm.
If a cycle is found before slow makes it way to head, then we found a different cycle. If slow makes it to head, then the cycle is to head.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With