题目:Linked List Cycle
难度:easy
问题描述:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题思路:
方法2:构造一个blank节点,遍历让所有的node.next都指向blank,仅最后一个不指向,如果最后尾节点未指向blank,则没有环,否则有环
方法2:遍历所有node,加入map,每次判断map中有没有
方法3:两点法,一个跑得快,一个跑得慢,慢的总会被追上,如果有环的话
代码如下:
public boolean hasCycle1(ListNode head) {
ListNode black = new ListNode(-1);
if(head==null) return false;
ListNode p = head;
while(p.next!=null){
ListNode t = p.next;
p.next = black;
p=t;
}
if(p==black) return true;
return false;
}
public boolean hasCycle2(ListNode head) {
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}
public boolean hasCycle3(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}