Skip to content

Instantly share code, notes, and snippets.

@gaoyike
Created June 23, 2014 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaoyike/f319f54ad7e9b9c4adea to your computer and use it in GitHub Desktop.
Save gaoyike/f319f54ad7e9b9c4adea to your computer and use it in GitHub Desktop.
2.6
/**
* Created by Readman on 6/23/14.
*/
public class detectcircular {
// time, if there is no circular, it will never stop. else n
// space, 1
public static ListNode detectcircular(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
break;
}
fast = slow;
slow = head;
while (fast != slow) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next= new ListNode(5);
head.next.next.next.next.next = head.next.next;
System.out.println(detectcircular(head).val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment