-
-
Save gaoyike/f319f54ad7e9b9c4adea to your computer and use it in GitHub Desktop.
2.6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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