您的位置:首页 > 其它

【leetcode】Linked List Cycle

2015-01-05 22:12 176 查看
问题描述:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?


思路:

1.遍历链表,比较set中是否包含节点的地址,如果包含说明是有环,如果不包含,则将地址存入到set中;

缺点:leetcdoe显示time limited

//time limited..
public boolean hasCycle1(ListNode head) {
if(head==null)
return false;
Set<String> address = new HashSet<String>();
while(head.next!=null){
System.out.println(head.toString());
if(address.contains(head.toString()))
break;
address.add(head.toString());
head=head.next;
}
if(head.next==null)
return false;
return true;
}


2.快慢指针:我很喜欢一个比喻,有两个人同时绕着操场跑,一个速度是另一个速度的两倍,这样以来两人肯定回碰到一起;快慢指针也是同理,在遍历时,让一个节点的后向遍历速度为next;另一个为next.next;如果有重复,两个指针肯定回碰到;

public boolean hasCycle(ListNode head) {
boolean result = false;
if(head==null)
return false;
ListNode flagA = head;
ListNode flagB = head;
while(flagB.next!=null&&flagB.next.next!=null){
flagA=flagA.next;
flagB=flagB.next.next;
if(flagA==flagB){
result = true;
break;
}
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: