141. Linked List Cycle
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.


解题要点:
Last updated
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.


Last updated
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list./**
* 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 pre = head;
ListNode cur = head.next;
while(pre != cur){
if(cur == null || cur.next == null) return false;
pre = pre.next;
cur = cur.next.next;
}
return true;
}
}