不用额外空间检查linked list是否有环。 快慢指针即可,如果有换,快指针肯定能追上慢指针,否则肯定不会。
/**
* 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 s1 = head;
ListNode s2 = head;
while( s2!=null )
{
if( s1.next==null || s2.next==null || s2.next.next==null )
{
return false;
}
s1 = s1.next;
s2 = s2.next.next;
if( s1 == s2 )
{
return true;
}
}
return false;
}
}
本文介绍了一种不使用额外空间判断链表是否存在环的方法:通过快慢两个指针遍历链表,快指针每次走两步,慢指针每次走一步。若存在环,快指针必定追上慢指针;反之,则不存在环。
258

被折叠的 条评论
为什么被折叠?



