链表 - Linked List Cycle
Linked List Cycle
描述:
Given a linked list, determine if it has a cycle in it.给定一个单链表,如何判断它是否存在闭环?
思路:
1、定义两个节点 slow(每次前进一步) fast(每次前进两部),且是快的先走
2、若存在一个环 肯定存一下两种情况
a、 slow.next == fast.next (存在闭环)
b、 slow.next == null || fast.next == null (不存在闭环)
算法:
/**
* 判断当前链表是否包含 闭环
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
* @return
*/
public boolean hasCycle(){
if(this.next == null){
System.out.println(0);
return false;
}
ListNode fast = this.next;
ListNode slow = this;
while (fast != null){
if(fast.next == null || fast.next.next == null){
return false;
}else {
fast = fast.next.next;
slow = slow.next;
}
if(fast == slow){
return true;
}
}
return false;
}