题目描述
判断给定的链表中是否有环
扩展:
你能给出不利用额外空间的解法么?
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题思路:利用快慢指针的性质,快慢指针相遇说明单链表中存在环
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 fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow)return true;
}
return false;
}
}