第(10)题 linked-list-cycle
知识点:链表
题述:Given a linked list, determine if it has a cycle in it.
题意是判断一个链表里是否存在环
思路:和上一题及其相似,只需判断是否存在环就可以了
代码如下:
/**
* 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) {
if(head == null || head.next == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
}