LinkedList - 141. Linked List Cycle
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos
which represents the position (0-indexed) in the linked list where tail connects to. If pos
is -1
, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
思路:
链表找环,两种做法,一种是用hash表来记录是否有走过这个节点,走过就是有环,第二种做法是快慢指针,快指针一次走两步,慢指针一次走一步,如果没有环,快指针先到达链表尾,如果有环,则快指针先进入环内转圈,等慢指针也进入环内,两个指针就一定会相遇。注意快指针是走两步,要避免空针的情况,比如当前fast指针走到倒数第二位,再走两步就会报空针。
代码:
java:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if ( fast == null || fast.next == null) return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}