判断链表是否为环形链表
这道题我采用 哈希表的形式,注意哈希表的一个特点是如果元素已经存在则不能添加,见http://Java 数组与集合(List, Set, Map)获取长度与遍历操作
最初我采用动态数组的方式有些测试用例过不去,利用哈希表这个特性可以使用
java
/**
* 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) {
Set<ListNode> visitnode=new HashSet<ListNode>(); //哈希表存储访问过的结点
while(head!=null){
if(!visitnode.add(head)){
return true; //如果添加结点失败,就说明结点之前已经存在
}
head=head.next;
}
return false;
}
}
环形链表Ⅱ:注意不允许修改链表,因此可以声明一个结点:

java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> visitnode=new HashSet<ListNode>();
ListNode p=head;
int flag=-1;
while(p!=null){
if(!visitnode.add(p)){
return p;
}
p=p.next;
flag++;
}
return null;
}
}
