Given a linked list, determine if it has a cycle in it.
判断一个链表是否有环,参考了网上的方法,设计一个快指针和慢指针,让它们互相追,有点像火车相遇问题,哈哈,代码如下,这里主要容易出现空指针问题,需要注意循环条件,另外将要入职华为了,真的开始做程序员,保持初心吧,但愿coding会一直是我的乐趣,而不是变成工作的烦恼。
/**
* 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) {
boolean flag = false;
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
flag = true;
break;
}
}
return flag;
}
}