Given a linked list, determine if it has a cycle in it.
代码如下:
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 if(head==null) 15 return false; 16 17 Map<ListNode,ListNode> map=new HashMap<>(); 18 while(head!=null) 19 { 20 if(map.get(head)!=head) 21 map.put(head,head); 22 else return true; 23 head=head.next; 24 } 25 return false; 26 } 27 }
浙公网安备 33010602011771号