题目
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
思路
需要注意的是,可能首尾成环,也可能在中间成环。使用快慢指针方法,慢指针步长为1,快指针步长为2。如果有环,则快慢指针总会在某点相遇。如果没有环,快指针会先为空。
代码
/**
* 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 a=head;
ListNode b=head;
while(true){
if(b.next==null || b.next.next==null){
return false;
}
a=a.next;
b=b.next.next;
if(a==b){
return true;
}
}
}
}