题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/**
* 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) {
//先判断头结点是否为空 如果为空返回false
if(head==null||head.next==null){
return false;
}
//建立快慢指针
ListNode slow = head;
ListNode fast = head.next;
//如果快慢指针不相等则一直循环
while (slow!=fast){
//判断快指针,快指针的下一个结点是否为空
if(fast == null || fast.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}