【Leetcode】142. Linked List Cycle II

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

思路

首先证明链表有环,再让一个指针从头开始,另一个指针从相遇的位置,每次都只走一步,相遇的地方就是链表的环开始的地方。

代码

public ListNode detectCycle(ListNode head) {
if (head == null) return null;
boolean flag = false;
ListNode fast = head, slow = head;

while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
flag = true;
break;
}
}

if (!flag) return null;

slow = head;
while (true) {
//先判断,避免只有两个节点的环的情况
if (slow == fast) return slow;
slow = slow.next;
fast = fast.next;
}
}

posted @ 2017-06-27 13:27  puyangsky  阅读(379)  评论(0)    收藏  举报