Created
June 8, 2015 14:07
-
-
Save cangoal/6a8989d2b6f0796e3c97 to your computer and use it in GitHub Desktop.
LeetCode - Linked List Cycle II
This file contains hidden or 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
| // | |
| public ListNode detectCycle(ListNode head) { | |
| if(head == null || head.next == null || head.next.next == null) return null; | |
| ListNode runner = head; | |
| ListNode walker = head; | |
| while(runner.next != null && runner.next.next != null){ | |
| runner = runner.next.next; | |
| walker = walker.next; | |
| if(runner == walker) break; | |
| } | |
| while(head != null && walker != null && head != walker){ | |
| head = head.next; | |
| walker = walker.next; | |
| } | |
| return walker; | |
| } | |
| // | |
| public ListNode detectCycle(ListNode head) { | |
| if(head==null) return head; | |
| ListNode walker = head; | |
| ListNode runner = head; | |
| while(runner.next!=null && runner.next.next!=null){ | |
| walker = walker.next; | |
| runner = runner.next.next; | |
| if(walker == runner) | |
| break; | |
| } | |
| if(runner.next==null || runner.next.next==null) return null; | |
| ListNode cur = head; | |
| while(cur!=runner){ | |
| cur = cur.next; | |
| runner = runner.next; | |
| } | |
| return cur; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment