使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点,如果存在环,那么这两个指针一定会相遇。https://leetcode.com/problems/linked-list-cycle/description/
/**
* 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) {//传入的是变量,后面应该用点(.)
ListNode *fastNode = head;
ListNode *slowNode = head;
if(fastNode.next !=null){//指针用->,变量用.
return false ;
}else{
fastNode = fastNode.next.next;//应该改成fastNode->next->next;
}
slowNode = slowNode.next;
if(slowNode == fastNode){
return true;
}
}
###########right
public class Solution {
public boolean hasCycle(ListNode head) {//传入的是变量
ListNode slow = head;//
ListNode fast = head;
while(fast != null && fast.next != null){//变量的next 用点(.)
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
}