Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
给一个链表,判断链表里是否有环,并且不使用额外的空间。
很简单,定义两个指针,slow和fast,fast每次步进2,slow每次步进1,如果fast遇到slow则有环,fast遇到null则无环。
/**
* 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) {
ListNode slow = head;
ListNode fast = head;
while (fast != null) {
slow = slow.next;
fast = fast.next;
if (fast == null) {
return false;
}
fast = fast.next;
if (slow == fast) {
return true;
}
}
return false;
}
}