141. The circular linked list
Given a list, the list is determined whether a ring.
To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.
Example 1:
Input: head = [3,2,0, -4] , pos = 1
Output: true
explanation: the list has a ring tail portion connected to a second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
explanation: the list has a ring, which is connected to the tail of the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
interpretation: the list does not ring.
Advanced:
You can use O (1) (ie, constant) memory to solve this problem?
/**
* 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.next;
ListNode slow = head;
while(fast != slow){
if(fast.next == null || fast.next.next == null) return false;
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}