题解 | #排序#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
通过hashmap来储存key为hashcode,值为node的map如果当有环时那么一定会有当这个head.next被存过,只要比对这个环的下一个节点是否在map中存在过,就可以判断是否有环了。 import java.util.*; /**
- 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) { HashMap mainTest = new HashMap(); while(head !=null ){ if(head.next == null){ return false; } if(head.next == mainTest.get(head.hashCode())) return true; mainTest.put(head.hashCode(),head.next); head = head.next; } return false; } }