Verify that Linked List is merging to run

I am trying to check if the last node of the linked list points to the head. This code seems to give a positive result for the problem, but also gives a false positive value for the list that contains the node pointing to the non-primary node.

I tried various things, such as checking if the slow node is equal to the head at the returned true point, but this does not 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?

+6
source share
2 answers
 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; } 

Well, the third time it's lovely.

If the cycle is detected before the slow movement begins, then we will find another cycle. If his head does slow, then the cycle should head.

+4
source
 public boolean isLinkedToStart(Node head) { if (head == null) { return false; } Node probe = head.next; while (probe != null) { if (probe == head) { return true; } if(probe.seen) { return false; } probe.seen = true; probe = probe.next; } return false; } 

Can you change the structure of the node or not? That is, you can add something like node.seen == false , and then switch this to a loop, and then change this ^ code to check that the nodes are invisible during the loop, and return false if it encounters " visible "node? (Implemented above)

+1
source

Source: https://habr.com/ru/post/956272/


All Articles