102. 带环链表
给定一个链表,判断它是否有环。
样例
```
样例 1:
输入: 21->10->4->5, then tail connects to node index 1(value 10).
输出: true
样例 2:
输入: 21->10->4->5->null
输出: false
```
挑战
不要使用额外的空间
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
if (head == null) return false;
ListNode temp = head;
ListNode next = head.next;
while (next!= null) {
next=next.next;
if (next == null) return false;
next=next.next;
temp=temp.next;
if (temp==next)return true;
}
return false;
}
}