Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.Follow up:
Can you solve it without using extra space?
public ListNode detectCycle(ListNode head) { if (head == null || head.next == null) { return null; } ListNode first = head; ListNode second = head; while (second != null) { second = second.next; if (second != null) { second = second.next; } else { return null; } first = first.next; if (second == first) { break; } } if (second == null) { return null; } else { ListNode node = head; while(second != node){ second = second.next; node = node.next; } return node; } }
Linked List Cycle II,布布扣,bubuko.com
原文地址:http://blog.csdn.net/u010378705/article/details/36025647