判断链表是否成环,还不能使用额外的空间。 使用快慢指针解决问题。 如果链表无环,那么慢指针无论如何是追不上快指针的。 但是如果存在环,肯定会存在快指针追上慢指针的情况存在。 根据这个道理实现以下代码
/**
* 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 && fast.next != null )
{
slow = slow.next;
fast = fast.next.next;
if( fast == slow )
{
return true;
}
}
return false;
}
}