(linkedlist)
| 2 | |
| 3 | |
| 4 | def findBeginning(linkedlist): |
| 5 | slow = linkedlist.head |
| 6 | fast = linkedlist.head |
| 7 | |
| 8 | # Find meetng point |
| 9 | while (fast != None) and (fast.next != None): |
| 10 | slow = slow.next |
| 11 | fast = fast.next.next |
| 12 | if fast == slow: |
| 13 | break |
| 14 | |
| 15 | # Check whether it is a circular linked list |
| 16 | if fast == None or fast.next == None: |
| 17 | return None |
| 18 | |
| 19 | # Move one runner to head. Making them move at same pace, they will meet at the beginning of the loop |
| 20 | fast = linkedlist.head |
| 21 | while fast != slow: |
| 22 | slow = slow.next |
| 23 | fast = fast.next |
| 24 | |
| 25 | return fast |
| 26 | |
| 27 | |
| 28 |