141. Linked List Cycle
2017-06-10 本文已影响3人
番茄晓蛋
**Description**Hints**Submissions**Solutions
Total Accepted: 177986
Total Submissions: 502453
Difficulty: Easy
Contributor: LeetCode
Given a linked list, determine if it has a cycle in it.
Follow up:Can you solve it without using extra space?
Hide Company Tags
Amazon Microsoft Bloomberg Yahoo
Hide Tags
Linked List Two Pointers
Hide Similar Problems
(M) Linked List Cycle II
/*
Use two pointers, slower and faster.
slower moves step by step. faster moves two steps at time.
if the Linked List has a cycle slower and faster will meet at some
point.
*/
public boolean hasCycle(ListNode head) {
ListNode slow = new ListNode(0);
ListNode fast = new ListNode(0);
slow.next = head;
fast.next = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}