141. Linked List Cycle

时间:2023-03-09 16:40:07
141. 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)
return false; Map<ListNode,ListNode> map=new HashMap<>();
while(head!=null)
{
if(map.get(head)!=head)
map.put(head,head);
else return true;
head=head.next;
}
return false;
}
}