描述
给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
挑战
不要使用额外的空间
代码
设置两个slow和fast指针,每次循环时,fast指针前进2步,slow前进1步,然后判断两个指针是否会相遇。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/*
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
// write your code here
if(head==null){
return false;
}
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null&&slow!=null&&slow.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return false;
}
}
本文介绍了一种不使用额外空间来判断链表是否存在环的方法。通过设置快慢两个指针,快指针每次移动两步,慢指针每次移动一步,如果链表中存在环,则两个指针最终会相遇。
270

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



